Created
November 17, 2019 23:34
-
-
Save yitonghe00/76a5f3034c9c81ebf8be3433e6865eae to your computer and use it in GitHub Desktop.
1099. Two Sum Less Than K (https://leetcode.com/problems/two-sum-less-than-k/): Given an array A of integers and integer K, return the maximum S such that there exists i < j with A[i] + A[j] = S and S < K. If no i, j exist satisfying this equation, return -1.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Sort + Two pointer solution | |
// Time: O(nlogn), 1ms | |
// Space: O(1), 36.7mb | |
class Solution { | |
public int twoSumLessThanK(int[] A, int K) { | |
// Sort the array first | |
Arrays.sort(A); | |
// Put pointers at begin/end and shrink | |
int l = 0, r = A.length - 1; | |
int ans = -1; | |
while(l < r) { | |
if(A[l] + A[r] < K) { | |
ans = Math.max(ans, A[l] + A[r]); | |
l++; | |
} else { | |
r--; | |
} | |
} | |
return ans; | |
} | |
} |
Nice!
niko
how is this with php?
I have only done it in python
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not bad!