O(nlogn) time


  • 0
    G

    public class Solution {

    public int findPairs(int[] nums, int k) {
    
    	Arrays.sort(nums);
    	Set<Integer> set = new HashSet<Integer>();
    	
    	for (int i = 0; i < nums.length; i++) {
    		
    		int index = this.binarySearch(nums, i + 1, nums.length - 1, nums[i] + k);
    		
    		if (index != -1)
    			set.add(nums[index]);
    	}
    	
    	return set.size();
    }
    
    private int binarySearch(int[] nums, int low, int high, int target) {
    	
    	while (high >= low) {
    		
    		 int mid = low + (high - low)/2;
    		 
    		 if (target > nums[mid])
    			 low = mid + 1;
    		 else if (target < nums[mid])
    			 high = mid - 1;
    		 else
    			 return mid;
    	}
    	
    	return -1;
    	
    }
    

    }


Log in to reply
 

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