Two pointer, Java


  • 0
    R
    public int findPairs(int[] nums, int k) {
    	Arrays.sort(nums);
    	int i = 0, j = 0, cnt = 0;
    		
    	while (i < nums.length) {
    		while (j < nums.length) {	
    	// equal to k add 1 to cnt
    			if (nums[j] - nums[i] == k ) 
    				cnt++;
    
    	// if the latter number equal to the previous one, we add 1 to j
    	// and j must be less than < length - 1 which means j <= length - 2
    			while (j < nums.length - 1 && nums[j+1] == nums[j])
    				j++;			
    
    			j++;
    		}
    
    		// move pointer i to next non-duplicate number, j to the number right after i
    		while (i < nums.length - 1 && nums[i+1] == nums[i] )
    			i++;
    
    		i++; j = i + 1;
    		}
    		return cnt;
    	}
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.