其他分享
首页 > 其他分享> > 剑指Offer 03 找出数组中重复的数字

剑指Offer 03 找出数组中重复的数字

作者:互联网

HashSet

/**
 * 题目:找出数组中重复的数字。
 * https://leetcode.cn/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/
 * 
 * 利用哈希集合在 O(1) 时间复杂度判断元素是否在集合中
 * */
public class Solution {
    public int findRepeatNumber(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (!set.add(nums[i])) {
                return nums[i];
            }
        }
        return -1;
    }
}

原地交换

/**
 * 找出数组中重复的数字。
 * 在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内
 * https://leetcode.cn/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/
 * */
public class Solution2 {
    public int findRepeatNumber(int[] nums) {
        for (int i = 0; i <nums.length; i++) {
            while (nums[i] != i) {
                if (nums[nums[i]] == nums[i]) {
                    return nums[i];
                }
                exch(nums, i, nums[i]);
            }
        }
        return -1;
    }

    private void exch(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

标签:03,shu,nums,int,zhong,Offer,数组,public
来源: https://www.cnblogs.com/liaozibo/p/offer-03.html