面试题03. 数组中重复的数字

//直接用HashSet 简单使用:https://blog.csdn.net/diaobao_weixiao/article/details/52784947    
//HashMap的遍历:https://www.cnblogs.com/meieiem/archive/2011/11/02/2233041.html
public static int findRepeatNumber(int[] nums) { HashSet t = new HashSet(); for(int n :nums){ if (!t.add(n)){ return n; } } return -1; }

  还有一位大哥使用的方法,比我的略好:

复制代码
public int findRepeatNumber(int[] nums) {
        for (int i = 0; i < nums.length ; i++) {
           //nums[i]可能为负(为负是因为这个下标对应的元素出现过了),所以应该用绝对值表示
            int index = Math.abs(nums[i]);
            if (nums[index]<0)
                return index;
            nums[index] *= (-1) ;
        }
        return 0;
    }
复制代码

 

posted @   贱人郭  阅读(135)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示