Skip to content

Instantly share code, notes, and snippets.

@leepro
Created September 2, 2013 02:55
Show Gist options
  • Save leepro/6408846 to your computer and use it in GitHub Desktop.
Save leepro/6408846 to your computer and use it in GitHub Desktop.
K-complementary
import java.util.Arrays;
class Solution {
public int solution(int K, int[] A) {
Arrays.sort(A);
return getKC(K, A);
}
public int getKC(int K, int[] A) {
int hit = 0;
int left = 0;
int right = A.length - 1;
// scan from right and from left, to the opposite direction
// left -----> <------ right
while(left <= right)
{
int tk = A[left] + A[right];
// K!
if(tk == K)
{
hit++;
// vice versa. (P,Q) pair, so (Q,P) hits one more time.
if(left!=right) hit++;
if(A[left]==A[left+1]) {
left++;
}
else if(A[right]==A[right-1])
{
right++;
}
else
{
left++;
right--;
}
} else if(tk < K) { // less than K
left++;
} else { // greater than K
right--;
}
}
return hit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment