Created
          September 2, 2013 02:55 
        
      - 
      
- 
        Save leepro/6408846 to your computer and use it in GitHub Desktop. 
    K-complementary 
  
        
  
    
      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
    
  
  
    
  | 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