1.数组中的重复元素

数组中重复的数字_牛客题霸_牛客网

方法1:暴力循环

import java.util.*;


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

方法2:hashset

import java.util.*;

public class Solution {
    public int duplicate (int[] numbers) {
        HashSet<Integer> set = new HashSet<Integer>();
        for(int i=0; i<=numbers.length-1; ++i){
            if(set.contains(numbers[i]))return numbers[i];
            else set.add(numbers[i]);
            //利用set的STL性质(add时有重复返回false)可以优化效率,将上面两句替换为:
            //if(!set.add(numbers[i]))return numbers[i];
        }
        return -1;
    }
}
//时间: HashSet/HashMap比较复杂,要根据N的规模分类讨论
//空间  O(N)

猜你喜欢

转载自blog.csdn.net/weixin_56194193/article/details/131504439