Leetcode 剑指offer 03 数组中重复的数字

题目链接:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof
找出数组中重复的数字。

在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1
的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。

首先我尝试了遍历整个数组来找到结果,结果显然是不行的。超出了时间限制。
所以我尝试了先排序再找。

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

利用sort()函数对nums数组进行排序后,查询数组中相邻两个元素是否有相等的。

posted @ 2021-05-10 21:40  子丶非鱼Zzz  阅读(45)  评论(0)    收藏  举报