Leetcode——287. 寻找重复数

首先很简单的做法即用哈希表记录数字出现的次数,最后循环哈希表输出value值不为1的key值。

cpp 复制代码
class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        unordered_map<int, int> map;
        for(int x : nums){
            map[x]++;
        }
        for(auto& entry : map){
            if(entry.second != 1){
                return entry.first;
            }
        }
        return 0;
    }
};

接着就是考虑高效算法,这里可以将数组看作一个链表,这个思想确实很巧妙,但也很难考虑到。

当看作是一个链表时,其任务就是找链表的环了。

如果允许修改原数组,即我们可以标记负号表示已经来过。

cpp 复制代码
class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        int idx = 0;
        while(nums[idx] > 0){
            int old = idx;
            idx = nums[old];
            nums[old] = -nums[old];
        }
        return idx;
    }
};

如果不允许修改原数组,则用快慢指针找环即可。

cpp 复制代码
class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        int slow = 0;
        int fast = 0;
        do{
            slow = nums[slow];
            fast = nums[nums[fast]];
        }while(slow != fast);
        
        fast = 0;
        while (fast != slow) {
            fast = nums[fast];
            slow = nums[slow];
        }
        return slow;
    }
};

注意,双指针解法需要从同一位置出发。

当然,此题也可用二分查找求解。

由于我们要找的数范围为1, n,所以取mid,遍历数组,如果<=mid的数字个数小于count,则说明1, mid范围上有数字少了,所以重复数字在mid, n区间。

cpp 复制代码
class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        int len = nums.size();
        int left = 0, right = len - 1;
        while(left < right){
            int mid = left + ((right - left) >> 1);
            int count = 0;
            for(int x : nums){
                if(x <= mid){
                    count++;
                }
            }
            if(count > mid){
                right = mid;
            }else{
                left = mid + 1;
            }
        }
        return left;
    }
};
相关推荐
Tairitsu_H9 分钟前
[C++高阶数据结构·图论上] 最小生成树:为什么“选边”和“选点”是两条路?
数据结构·c++·图论·最小生成树
Navigator_Z33 分钟前
LeetCode //C - 1313. Decompress Run-Length Encoded List
c语言·算法·leetcode
Bczheng135 分钟前
VS2022 安装MFC和QT
c++·qt·mfc
dialect_1 小时前
CODEFORCES ROUND 1127 DIV2
开发语言·c++·算法
Nuanyt1 小时前
LeetCode Hot 100 链表专题(四)· 3 题(Java)
java·算法·leetcode·链表·双指针
悠仁さん9 小时前
【C++】AVL 树
c++
wuminyu10 小时前
JVM规范学习总结:解释器与JIT编译器如何处理JVM字节码
java·linux·c语言·jvm·c++
小徐不徐说10 小时前
序列化与反序列化:把 C++ 对象可靠地保存下来
开发语言·数据库·c++·php
ragnwang10 小时前
Notes: Python pybind11 import C++ module
开发语言·c++·python
充值内卷11 小时前
我给桌面加了个鱼缸:C++ 写后端,WebView2 里养一座 Three.js 小岛
开发语言·javascript·c++