Home > Java > javaTutorial > How to determine if there are duplicate elements in Java

How to determine if there are duplicate elements in Java

WBOY
Release: 2023-05-03 21:31:05
forward
2532 people have browsed it

Given an integer array, determine whether there are duplicate elements. The function returns true if any value appears at least twice in the array. Returns false if every element in the array is different.

示例 1:
输入: [1,2,3,4]
输出: true
Copy after login

Method 1: Sorting time complexity is O (NlogN) space complexity is O (logN)

nums.sort()
for i in range(len(nums)-1):
    #判断前一个与后一个数是否相等
    if nums[i] == nums[i+1]:
        return  True
return False
Copy after login

Method 2: Hash table

dic = {}
for i in range(len(nums)):
    if nums[i] in dic:
        return True
    else:
        dic[nums[i]] = 1
return False
Copy after login

The above is the detailed content of How to determine if there are duplicate elements in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template