当前位置:网站首页>leetcode 217存在重复元素
leetcode 217存在重复元素
2022-08-08 21:07:00 【胖丁微笑】
给你一个整数数组 nums 。如果任一值在数组中出现 至少两次 ,返回 true ;如果数组中每个元素互不相同,返回 false 。

方法一
//java Set自带去重,如果去重后的长度小于原长度,则返回true
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> res = new HashSet<Integer>(); //创建一个新的set集合
for(int i : nums) {
//用foreach循环进行遍历
res.add(i);
}
return IntStream.of(nums).distinct().count() != nums.length;
}
}
方法二:
//对数组进行排序,它们会按大小拍好,如果相邻的数字有相等的,则证明有重复元素
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums); //arrays.sort方法进行排序
int n = nums.length;
for (int i = 0; i < n - 1; i++) {
if (nums[i] == nums[i + 1]) {
return true;
}
}
return false;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/contains-duplicate/solution/cun-zai-zhong-fu-yuan-su-by-leetcode-sol-iedd/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
边栏推荐
猜你喜欢
Introduction to GeoServer: 01-Introduction

1天搞定单片机中断——基础知识大全

昇腾Ascend 随记 —— 昇腾 AI 的基本架构
GeoServer introductory study: 07 - release a larger multi-tiered TIF map data

目标检测论文 Precise detection of Chinese characters in historical documents with DRL

昇腾Ascend 随记 —— TensorFlow 模型迁移

day4——乐优商城项目结构(6个微服务)

手机投影到deepin
GeoServer Getting Started Learning: 06-Publishing Multi-level TIF Map Data

jmeter简单压测
随机推荐
day4——乐优商城项目结构(6个微服务)
Members that must be initialized for initial column initialization
SQL注入之搭建dnslog
deepin系统入门记录
【时间戳转普通时间格式的方法】
GeoServer Getting Started Learning: 06-Publishing Multi-level TIF Map Data
C语言求积分的近似值
C语言打印九九乘法表
记录非Gui模式Jmeter使用
window下socket(TCP)控制台程序
图神经网络GNN简介及应用方向
ESLint: The Function constructor is eval. (no-new-func)错误解决
unity报Unable to load the icon: 'CacheServerDisconnected'时的解决办法
360杜跃进ISC演讲:保障信创软件的可信性和安全性是信创安全体系的基础
[MEF]第05篇 MEF的目录(Catalog)筛选
阿里云祝顺民:算力网络架构的新探索
charles简单使用
wp-ctfshow-web10 (group up注入)
fashion CNNs code
Educational Codeforces Round 112 D. Say No to Palindromes