题解 | #数组中重复的数字#

数组中重复的数字

http://www.nowcoder.com/practice/6fe361ede7e54db1b84adc81d09d8524

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param numbers int整型一维数组 
     * @return int整型
     */
    public int duplicate (int[] numbers) {
        // write code here
        //思路:遍历,然后统计每一个数字的个数,返回任意一个就行
        if(numbers == null || numbers.length == 0){
            return -1;
        }
        //方法一:用set进行判断
        HashSet<Integer> hashset = new  HashSet<>();
        for(int i : numbers){
            if(hashset.contains(i)){
                return i;
            }else{
                hashset.add(i);
            }
        }
        return -1;
        //方法二:新建一个数组,将原数组中的每一个数字当做新数组的下标,而新数组中存放每个下标出现的次数。
        //这是一种及其重要的思想
        int[] res = new int[numbers.length];
        for(int i : numbers){
            res[i]++;
            if(res[i] == 2){
                return i;
            }
        }
        return -1;
    }
}
全部评论
第二个方法不行啊,32行的res[i],这个i会超过数组的numbers.length这个值,导致下标越界!
5 回复 分享
发布于 2022-03-09 22:42
思想很好,但是就是越界了,哈哈
1 回复 分享
发布于 2022-05-31 10:07
public int duplicate (int[] numbers) { if(numbers == null || numbers.length == 0){ return -1; } int max = numbers[0]; for(int n : numbers){ if(max < n){ max = n; } } //桶排序思想 int[] res = new int[max + 1]; for(int i : numbers){ res[i]++; if(res[i] == 2){ return i; } } return -1; }
点赞 回复 分享
发布于 2022-06-20 16:33

相关推荐

不愿透露姓名的神秘牛友
06-23 18:33
点赞 评论 收藏
分享
Ncsbbss:又想干活又想要工资,怎么什么好事都让你占了
点赞 评论 收藏
分享
05-22 12:44
已编辑
门头沟学院 golang
点赞 评论 收藏
分享
评论
29
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务