剑指offer-AcWing 13. 找出数组中重复的数字

https://www.acwing.com/problem/content/description/14/


给定一个长度为 n 的整数数组 nums,数组中所有的数字都在 0∼n−1 的范围内。
数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。
请找出数组中任意一个重复的数字。
注意:如果某些数字不在 0∼n−1 的范围内,或数组中不包含重复数字,则返回 -1;

数据范围
0≤n≤1000
样例
给定 nums = [2, 3, 5, 4, 3, 2, 6, 7]。
返回 2 或 3。


点击查看代码
class Solution {
public:
    //前面有重复的不能返回nums[i],若后面有不符合要求的返回-1!!!
    // 
    int duplicateInArray(vector<int>& nums) {
        if(nums.size() == 0) return -1;
        int st[1011];
        memset(st,0,sizeof st);
        bool isok = true;
        int ans = -1; //如果所有数字都在0~n-1,不包含重复数字,也要返回-1
        for(int i = 0; i < nums.size(); i++){
            if(nums[i] < 0 || nums[i] > nums.size()-1){
                isok = false;
            }
            if(st[nums[i]] != 0) ans = nums[i];
            st[nums[i]] = 1;
        }
        if(isok && isok != -1) return ans;
        return -1;
    }
};

posted @ 2022-04-18 15:02  超级氯化钾  阅读(29)  评论(0)    收藏  举报