思路1:对于排序后的数组,通过前后两个元素进行比较判定是否存在重复数字

代码实现

C++

class Solution {
public:
    int findRepeatNumber(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size(); ++ i) {
            if (nums[i] == nums[i+1])
                return nums[i];
        }
        return -1;
    }
};

Python

class Solution:
    def findRepeatNumber(self, nums: List[int]) -> int:
        nums.sort()
        for i in range(1,len(nums)):
            if nums[i]==nums[i-1]:
                return nums[i]
        return -1

思路2:哈希表,返回count>1的元素

Python

class Solution:
    def findRepeatNumber(self, nums: List[int]) -> int:
        from collections import Counter
        num=Counter(nums)
        for key in num:
            if num[key]>1:
                return key
        return -1         

C++

class Solution {
public:
    int findRepeatNumber(vector<int>& nums) {
        unordered_map<int, bool> map;
        for(int num : nums) {
            if(map[num]) return num;
            map[num] = true;
        }
        return -1;
    }
};