There are duplicate elements in Android LeetCode

Posted by deejay on Tue, 08 Oct 2019 05:54:57 +0200

Given an array of integers, determine whether duplicate elements exist.

If any value appears in the array at least twice, the function returns true. If each element in the array is different, false is returned.

Example 1:

Input: [1, 2, 3, 1]
Output: true

Example 2:

Input: [1, 2, 3, 4]
Output: false

Source: LeetCode
Link: https://leetcode-cn.com/problems/contains-duplicate
 

Study the problem

First is the first.

int[] arr = new int[]{0, 8, 13, 52, 55, 5545, 33, 442, 23474, 12234, 244, 52, 4, 22, 8, 12, 4, 8};

        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < i; j++) {
                if (arr[i] == arr[j]) {
                    System.out.println("   j:  " + j + " i :" + i + "   " + arr[i]);
                    return;
                }
            }
        }

This corresponds to

Solution 2,3

Use of tools

If it's a duplicate element, they should be adjacent after sorting.

 int[] arr = new int[]{0, 8, 13, 52, 55, 5545, 33, 442, 23474, 12234, 244, 52, 4, 22, 8, 12, 4, 8};

        Arrays.sort(arr);

        for (int i = 0; i < arr.length - 1; i++) {

            if (arr[i] == arr[i + 1]) {
                System.out.println(" " + arr[i]);
                return;
            }
        }
   int[] arr = new int[]{0, 8, 13, 52, 55, 5545, 33, 442, 23474, 12234, 244, 52, 4, 22, 8, 12, 4, 8};

        HashSet<Integer> hashSet = new HashSet<>();
        for (int x : arr) {
            if (hashSet.contains(x)) {
                System.out.println(" x  " + x);
                return;
            }
            hashSet.add(x);
        }


        List<Integer>  list=new ArrayList<>();
        for (int x : arr) {
            if (list.contains(x)) {
                System.out.println(" x  " + x);
                return;
            }
            list.add(x);
        }

If there is no element in the collection, add it to the collection. If there is one, it's found. It's almost the same as the first one.