LeetCode - duplicates exist

Given an array of integers, check if there are duplicate elements.

The function should return true if any value appears in the array at least twice. Returns false if each element is different.

Implementation idea: We assume that the elements in the array are not repeated, compare the elements in the array pairwise, use the first element in the array to compare with all subsequent elements, then use the second element in the array to compare with the subsequent elements, and so on Implement pairwise comparison. If there is a group of elements that are the same, the array will store duplicates and end the loop. Store the result of the comparison in a flag variable, and finally determine the value of the flag variable.

class Solution {
    public boolean containsDuplicate(int[] nums) {
        boolean flag =false;
        for(int i=0;i<nums.length-1;i++){
            for(int j=i+1;j<nums.length;j++){
                if(nums[i]==nums[j]){
                    flag =true;
                    System.out.println("重复的值为"+nums[i]);
                    break;
                }
            }
        }
        if(flag){
            System.out.println("有重复元素");
        }else{
            System.out.println("没有重复元素")
        }
        return flag;
    }
    public static void main(String[] args){
        Solution sl =new Solution();
        int[] nums={1,2,3,3,5,6};
        System.out.println(sl.Solution(nums));
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325993172&siteId=291194637