博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
217. Contains Duplicate
阅读量:2352 次
发布时间:2019-05-10

本文共 1122 字,大约阅读时间需要 3 分钟。

题目

Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

Input: [1,2,3,1]

Output: true

我的想法

查询类的题目首先想到的是hashset和hashmap

class Solution {
public boolean containsDuplicate(int[] nums) {
Set
set = new HashSet<>(); for(int i = 0; i < nums.length; i++){
if(set.contains(nums[i])) return true; set.add(nums[i]); } return false; }}

因为只判断是否含有,不考虑index,可以用双指针

性能比上一个方法更好

class Solution {
public boolean containsDuplicate(int[] nums) {
if(nums.length < 2) return false; Arrays.sort(nums); for(int i = 0, j = 1; j < nums.length; i++, j++){
if(nums[i] == nums[j]) return true; } return false; }}

解答

j这个变量完全可以省去,边界条件可以放在for循环中判断

public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums); for (int i = 0; i < nums.length - 1; ++i) {
if (nums[i] == nums[i + 1]) return true; } return false;}

转载地址:http://ubqvb.baihongyu.com/

你可能感兴趣的文章
ZooKeeper 安装部署
查看>>
ZooKeeper 配置
查看>>
11.组合模式--Composite
查看>>
12.轻量模式--Flyweight
查看>>
13.外观模式--Facade
查看>>
开源史上最成功的八个开源软件
查看>>
More Effective C++读书笔记
查看>>
关于assert,ASSERT,TRACE和VERIFY
查看>>
关于C++中野指针的说明
查看>>
Linux/Unix环境下的make和makefile详解
查看>>
SourceInsight添加对汇编语言文件.s和.S的支持
查看>>
windows 下实现函数打桩:拦截API方式
查看>>
获取Windows系统版本
查看>>
漫谈兼容内核之十二:Windows的APC机制
查看>>
21.windbg-.lastevent、!analyze(dump分析、异常错误码查询)
查看>>
16.windbg-.frame、dt(切换局部上下文、查找结构体)
查看>>
开源任务管理器 Process Hacker (Windows)
查看>>
快速发现Windows中毒的工具:Process Hacker
查看>>
Process Hacker源码中的用户态hook的做法
查看>>
Get IT技能知识库 50个领域一键直达
查看>>