当前位置: 移动技术网 > IT编程>开发语言>Java > 剑指 Offer 03. 数组中重复的数字

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

2020年07月13日  | 移动技术网IT编程  | 我要评论

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

在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

方法1: 额外空间(自己解题思路)

创建一个数组记录重复情况
时间复杂度O(n),空间复杂度高O(n)

class Solution {
    public int findRepeatNumber(int[] nums) {
        int[] order=new int[nums.length];
        for(int i=0;i <nums.length;i++){
        	if(order[nums[i]]!=0) {
        		return nums[i];
        	}
            order[nums[i]]=1;
        }
        return 0;
    }
}

改进:可利用Set的不重复性质

方法2:特殊的哈希结构

时间复杂度:O(n),空间复杂度 O(1)

public int findRepeatNumber(int[] nums) {
        for (int i = 0; i < nums.length ; i++) {
            int index = Math.abs(nums[i]);
            if (nums[index]<0)
                return index;
            nums[index] *= (-1) ;
        }
        return 0;
    }

方法3:置换

时间复杂度:O(n),空间复杂度 O(1)

public int findRepeatNumber(int[] nums) {
        for(int i=0;i <nums.length;i++){
        	if(i!=nums[i]&&nums[i]==nums[nums[i]])
        		return nums[i];
            else{
                int tmp=nums[i];
                nums[i]=nums[nums[i]];
                nums[tmp]=tmp;
            }
        }
        return 0;
    }

本文地址:https://blog.csdn.net/weixin_38941866/article/details/107248938

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网