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

数组中重复的数字

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

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param numbers int整型一维数组 
     * @return int整型
     */
    public int duplicate (int[] numbers) {
        int[] map = new int[numbers.length];
        for(int index = 0; index < numbers.length; index++) {
            int val = numbers[index];
            int count = map[val];
            if(count == 0) {
                count = count + 1;
            } else {
                count = count + 1;
            }
            map[val] = count;
        }
        for(int index =0; index < map.length; index ++) {
            int count = map[index];
            if(count > 1) {
                return index;
            }
        }
        return -1;
    }
}

还有暴力破解方法,两层for循环解决;太简单了。时间复杂度是n~2;

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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