current position:Home>Force deduction brush question 217 There are duplicate elements

Force deduction brush question 217 There are duplicate elements

2022-05-15 05:30:47GRT should keep working hard

 Insert picture description here
Train of thought : Sort the array ,Arrays.sort(). If the same element appears , It should be in an adjacent position .

class Solution{
    
    public boolean remove(int[] num){
    
        Arrays.sort(num);
        for (int i = 0; i < num.length; i++) {
    
            if (num[i] == num[i+1]){
    
                return true;
            }
        }
        return false;
    }
}

Train of thought two : use hashset Methods , If you can't add it to the collection , It indicates that the same element exists .

class Solution2{
    
    public boolean remove2(int[] num){
    
        HashSet<Integer> integers = new HashSet<>();
        for (int i = 0; i < num.length; i++) {
    
            if (!(integers.add(num[i]))){
    
                return true;
            }
        }
        return false;
    }
}

copyright notice
author[GRT should keep working hard],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/135/202205142234159970.html

Random recommended