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

题目:

找出数组中重复的数字。


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

示例 1:

输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
 

限制:

2 <= n <= 100000

解答:

方法一:用冗余数组记录数字重复出现的次数。

public class Solution {
    // Parameters:
    //    numbers:     an array of integers
    //    length:      the length of array numbers
    //    duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;
    //                  Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
    //    这里要特别注意~返回任意重复的一个,赋值duplication[0]
    // Return value:       true if the input is valid, and there are some duplications in the array number
    //                     otherwise false
    public boolean duplicate(int numbers[],int length,int [] duplication) {
        int a[] = new int[length];
        for(int i = 0;i<length;i++){
            a[numbers[i]]++;
            if(a[numbers[i]]>1){
                duplication[0] = numbers[i];
                return true;
            }
        }
        return false;
        
    }
}

方法二:

用JAVA中的集合类(Set)判断一个数是否出现多次(if(!set.add(num))

Set类的add()方法:在执行add方法时候,如果这个元素已经在set中存在,那么就返回false,否则返回true。

set的定义: Set<Integer> set = new HashSet<Integer>();//HashSet是Set的一个实现类;

class Solution {
    public int findRepeatNumber(int[] nums) {
        Set<Integer> set = new HashSet<Integer>();
        int duplicate = -1;
        for(int num : nums){
            if(!set.add(num)){
                duplicate = num;
                break;
            }
        }
        return duplicate;
    }
}

 

方法三:原地交换(原理是什么,思路是怎么想到的?)、

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

 

posted @ 2020-07-01 11:43  3KBLACK  阅读(60)  评论(0编辑  收藏  举报