This is the 10th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Topic Description:

217. Duplicate elements exist – Force button (LeetCode) (leetcode-cn.com)

Given an array of integers, determine whether there are duplicate elements.

This function returns true if a value appears at least twice in the array. Return false if each element in the array is different.

The sample a

Input: [1,2,3,1] output: trueCopy the code

Example 2

Input: [1,2,3,4] output: falseCopy the code

Example 3

Input: [1,1,1,3,3,4,3,2,4,2] output: trueCopy the code

Thought analysis

The sorting

And this one is pretty simple. After sorting, if you have duplicate elements, they must be adjacent.

So all we have to do is sort, and then we’re going to go through and compare the two adjacent elements to see if they’re equal.

Note:

Sort here direct use of Java underlying sort on the line, write their own general beat –

AC code

class Solution {
    fun containsDuplicate(nums: IntArray): Boolean {
        Arrays.sort(nums)
        
        for (i in 0..nums.lastIndex - 1) {
            if (nums[i] == nums[i+1]) {
                return true}}return false}}Copy the code

Hash table

Here, as usual, we take advantage of the fact that we cannot add repeating elements to a set

We can iterate through the array, insert elements into the hash table, and if the addition fails, it’s a repeat.

You can also compare the lengths of the hash table to the original array, and if they are not equal, it means that there are duplicate elements.

And notice here that there’s a lot of advanced syntax that you can use if you’re doing things in Kotlin

But shorter code is not always better, and some lines of code are both time and space complex.

AC code

class Solution {
    fun containsDuplicate(nums: IntArray): Boolean {
        return nums.size > nums.toSet().size
    }
}
Copy the code
class Solution {
    fun containsDuplicate(nums: IntArray): Boolean {
        // Distinct () is removed internally from a set
        return nums.size > nums.distinct().count()
    }
    
}
Copy the code
class Solution {
    fun containsDuplicate(nums: IntArray): Boolean {
         val set = hashSetOf<Int> ()for (n in nums){
            if(!set.add(n)) {
                return true}}return false}}Copy the code

conclusion

This problem is too simple, I can 😊 again

Similar problems can be solved by referring to this problem

reference

Duplicate elements exist – Duplicate elements exist – Force button (LeetCode) (leetcode-cn.com)