美文网首页
剑指 Offer 03. 数组中重复的数字

剑指 Offer 03. 数组中重复的数字

作者: 7ccc099f4608 | 来源:发表于2021-03-07 15:13 被阅读0次

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

image.png

(图片来源https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/

日期 是否一次通过 comment
2021-03-07 0

/** 遍历 */
public int findRepeatNumber(int[] nums) {
        if(nums == null || nums.length < 1) {
            return -1;
        }

        for(int i=0; i<nums.length; i++) {
            while(nums[i] != i) {
                if(nums[i] == nums[nums[i]]) {
                    return nums[i];
                }

                swap(nums, i, nums[i]);
            }
        }

        return -1;
    }

    private void swap(int[] nums, int l, int r) {
        int tmp = nums[l];
        nums[l] = nums[r];
        nums[r] = tmp;
    }

相关文章

网友评论

      本文标题:剑指 Offer 03. 数组中重复的数字

      本文链接:https://www.haomeiwen.com/subject/ethyqltx.html