Why the output is wrong ??


  • 1
    U

    for [1,2,3,4,5] and k=-1 , are (2,1) (3,2) (4,3) (5,4) not pairs
    Expected Output : []

    class Solution {
    public:
        int findPairs(vector<int>& nums, int k) {
            set<pair<int,int> > s;
            if(nums.size()==0){
                return 0;
            }
            sort(nums.begin(),nums.end());
            if(k==0){
                for(int i=0;i<nums.size()-1;i++){
                    if(nums[i]==nums[i+1]){
                        s.insert(make_pair(nums[i],nums[i+1]));
                    }
                }
                return s.size();
            }
            
            for(int i=0;i<nums.size();i++){
                if(binary_search(nums.begin(),nums.end(),nums[i]+k)){
                    s.insert(make_pair(nums[i],nums[i]+k));
                }
            }
            return s.size();
        }
    };
    

  • 2

    Because (1,2) has absolute difference 1, not -1. Note that (1,2) is the same as (2,1), and absolute difference is |1-2| = |2-1| = 1


  • 0
    M

    I had the same problem. Essentially you have to check if k is negative.


Log in to reply
 

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