The existence of repeated elements in the LeetCode data structure

Get into the habit of writing together! This is the 9th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

topic

there are duplicate elements

gives you an integer array nums. Returns true if any value appears in the array at least twice; returns false if each element in the array is different from each other.  

Example 1:

输入:nums = [1,2,3,1]
输出:true
复制代码

Example 2:

输入:nums = [1,2,3,4]
输出:false
复制代码

Example 3:

输入:nums = [1,1,1,3,3,4,3,2,4,2]
输出:true
复制代码

hint:

1 <= nums.length <= 105
-109 <= nums[i] <= 109
复制代码

answer

problem-solving analysis

This question is a simple level of Leetcode, mainly to examine everyone's mastery of basic data structures. The basic data structure is nothing more than: linear table, stack, queue, string, array, generalized table, tree, binary tree, graph, sorting, search and so on. Let's take a look at the two solutions of sorting and hashing.

1. Sorting method

Sort first, then traverse the array, if they nums[i -1 ] == nums[i]are equal , return true, if they are not satisfied, then return false.

Using the Java language to answer the questions, we can use the system method Arrays.sortto sort the array, the bottom layer uses the quick sort algorithm, and the time complexity of array sorting is O(log(n))

Time Complexity: O(NlogN)
Space Complexity: O(logN)

2. Hash table method

Create a hash table, and then store the array in the hash table to determine whether the added hash table is repeated, if it is repeated, return true, if it does not exist, return false.

Time Complexity: O(N)
Space Complexity: O(N)

problem solving code

The solution code is as follows (detailed comments in the code):

  1. The code for sorting and solving the problem is as follows:
class Solution {
    public boolean containsDuplicate(int[] nums) {
        // 排序,jdk 采用快速排序的方式
        Arrays.sort(nums);
        for (int i = 1; i < nums.length; i++) {
            if (nums[i -1 ] == nums[i]) {
                return true;
            }
        }
        return false;
    }
}
复制代码
  1. Hash method, the code to solve the problem is as follows:
class Solution {
    public boolean containsDuplicate(int[] nums) {
        HashSet<Integer> set = new HashSet<>(nums.length);
        for (int i = 0; i < nums.length; i++) {
            if (!set.add(nums[i])) {
                return true;
            }
        }
        return false;
    }
}
复制代码

Feedback results after submission (sorting method is used, since the topic has not been optimized, the performance is general):

image.png

Reference Information

Guess you like

Origin juejin.im/post/7084981463057170462