剑指OFFER----面试题03. 数组中重复的数字

链接:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/

思路:

  首先判断边界情况,然后对数组进行遍历,如果遍历的当前数字不在数组中的对应位置,则将他们进行交换,否则即数组中对应位置已经有数组,则为重复数字。

代码:

时间复杂度:O(N)

空间复杂度:O(1)

class Solution {
public:
    int findRepeatNumber(vector<int>& nums) {
        int n = nums.size();
        for (auto x: nums) {
            if (x < 0 || x >= n) return -1;
        }
        for (int i = 0; i < n; ++i) {
            while (i != nums[i] && nums[i] != nums[nums[i]]) swap(nums[i], nums[nums[i]]);
            if (i != nums[i] && nums[i] == nums[nums[i]]) return nums[i];
        }
        return -1;
    }
};

猜你喜欢

转载自www.cnblogs.com/clown9804/p/12307850.html