Get the App
SLTechnology News&Howtos  ›  Development  › 

How can Python determine whether there are duplicate elements in an array of integers

Shulou Source: shulou.com Published: 2022-06-02 05:51:24 10月02日 Update

This article mainly explains "how to judge whether there are repeating elements in an integer array by Python". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to determine whether there are repeating elements in an integer array by Python".

Question: given an array of integers, how do you determine whether there are duplicate elements?

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

Example 1:

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

Example 2:

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

Example 3:

Input: [1, true, 1, 1, 3, 3, 4, 3, 4, 4, 2] output:

Ideas for solving the problem:

Sort the array, and if two consecutive numbers are equal, it proves that there are duplicate elements.

Directly use the hash set: create a new hash collection and add elements to the collection one by one. If the element is not successfully added, it proves that there is a duplicate element and returns True or False.

Code:

The hash set used here to solve the problem

Java:

Class Solution {public boolean containsDuplicate (int [] nums) {Set set = new LinkedHashSet (); for (int num: nums) {if (! set.add (num)) return true; / / failed to join the collection, which proves that there is already a same element in the collection and returns False} return false;}}

Python:

The set () function in Python can directly convert an array into a hash set. Directly compare whether the length of the transformed hash set is equal to the length of the original array, the equality proves that the original array has no repetitive elements, and the unequal proves that the original array contains repetitive elements.

Class Solution: def containsDuplicate (self, nums: List [int])-> bool: return len (nums)! = len (set (nums)) # so far, I believe you have a deeper understanding of "how Python determines whether there are duplicate elements in an integer array". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Element array hash integer example length input output same success content function learning practical deeper two code interest practicality practice Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info NVidia vpn Docker Microsoft