leetcode:Contains Duplicate和Contains Duplicate II
一、Contains Duplicate
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.
分析:先把数组排个序,然后遍历排序后的数组,查看相邻元素是否有重复,时间复杂度O(nlogn)。
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
if( (nums.size() == 0) || (nums.size() == 1) ) return false;
std::sort(std::begin(nums), std::end(nums)); //sort()是c++、java里对数组的元素进行排序的方法,包含于头文件algorithm。
for(int i = 0; i < nums.size()-1; i++)
if(nums[i] == nums[i+1]) return true;
return false;
}
};
其他解法:(集和多集的区别是:set支持唯一键值,set中的值都是特定的,而且只出现一次;而multiset中可以出现副本键,同一值可以出现多次。)
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
set<int> s(nums.begin(), nums.end());
if (nums.size() == s.size()) return false;
else return true;
}
};
或者:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
vector <bool> vec;
vec.push_back(false);
if (nums.size()<=1){
return false;
}
for (int i=0; i<nums.size();i++){
int m=nums[i];
if (m>=vec.size()){
for (int j=vec.size();j<=m;j++){
vec.push_back(false);
}
}
if (m<vec.size()){
if (vec[m]==true){
return true;
}
else{
vec[m]=true;
}
}
}
return false;
}
};
或:sort the vector then traverse to find whether there are same value element continuesly:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
sort(nums.begin(), nums.end());
if (nums.size() == 0){
return false;
}
vector<int>::iterator it = nums.begin();
int temp = *it;
it++;
for (; it != nums.end(); it++){
if (*it == temp){
return true;
}
temp = *it;
}
return false;
}
};
或: step 1 Sort the vector
step2 use erase to remove the duplicate and compare the size of the vector
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
int pre = nums.size();
sort(nums.begin(), nums.end());
nums.erase(unique(nums.begin(), nums.end()), nums.end());
int post = nums.size();
return (post == pre) ? false : true;
return false;
}
};
或:use hash map
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_map<int, int> hash;
vector<int>::iterator it = nums.begin();
for (; it != nums.end(); it++){
if (hash.find(*it) != hash.end()){
return true;
}
hash[*it] = 1;
}
return false;
}
};
二、Contains Duplicate II
Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.(注:at most 最多)
分析:题意为---给一个整型数组及整数k,找出是否存在不同的i和j使得nums[i] = nums[j]且i 和j之差最多为k
代码如下:
The basic idea is to maintain a set s which contain unique values from nums[i - k] to nums[i - 1], if nums[i] is in set s then return true else update the set.
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k)
{
unordered_set<int> s;
if (k <= 0) return false;
if (k >= nums.size()) k = nums.size() - 1;
for (int i = 0; i < nums.size(); i++)
{
if (i > k) s.erase(nums[i - k - 1]);
if (s.find(nums[i]) != s.end()) return true;
s.insert(nums[i]);
}
return false;
}
};
或:
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if (!k)
return false;
// fill set
unordered_set<int> h;
size_t size = k<nums.size()?k:nums.size();
for(int i=0;i<size;++i){
if(h.find(nums[i])!=h.end()) //find(value)返回value所在位置,找不到value将返回end()
return true;
h.insert(nums[i]);
}
// check dublicates
size = nums.size();
for(int i=k;i<size;++i){
if(h.find(nums[i])!=h.end())
return true;
h.erase(nums[i-k]); //erase(value) 移除set容器内元素值为value的所有元素,返回移除的元素个数
h.insert(nums[i]);
}
return false;
}
};
或:
其中:unique()函数是一个去重函数,STL中unique的函数 unique的功能是去除相邻的重复元素(只保留一个),还有一个容易忽视的特性是它并不真正把重复的元素删除。他是c++中的函数,所以头文件要加#include<iostream.h>,具体用法如下:
int num[100];
unique(num,mun+n)返回的是num去重后的尾地址,之所以说比不真正把重复的元素删除,其实是,该函数把重复的元素一到后面去了,然后依然保存到了原数组中,然后返回去重后最后一个元素的地址,因为unique去除的是相邻的重复元素,所以一般用之前都会要排一下序。
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if(nums.empty()||k<1)
return false;
vector<int> temp=nums;
sort(temp.begin(),temp.end());
auto it=unique(temp.begin(),temp.end());
if(it==temp.end())
return false;
for(auto it1=nums.begin();it1!=nums.end()-1;++it1){
auto it2=find(it1+1,nums.end(),*it1); //从it1+1到nums.end()查找与指向it1的值相同的索引
if(it2!=nums.end()){
if(it2-it1<=k){
return true;
}
}
}
return false;
}
};
leetcode:Contains Duplicate和Contains Duplicate II的更多相关文章
- LeetCode(220) Contains Duplicate III
题目 Given an array of integers, find out whether there are two distinct indices i and j in the array ...
- [LeetCode] 95. Unique Binary Search Trees II(给定一个数字n,返回所有二叉搜索树) ☆☆☆
Unique Binary Search Trees II leetcode java [LeetCode]Unique Binary Search Trees II 异构二叉查找树II Unique ...
- 【python】Leetcode每日一题-反转链表 II
[python]Leetcode每日一题-反转链表 II [题目描述] 给你单链表的头节点 head 和两个整数 left 和 right ,其中 left <= right .请你反转从位置 ...
- 【LeetCode】522. Longest Uncommon Subsequence II 解题报告(Python)
[LeetCode]522. Longest Uncommon Subsequence II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemin ...
- 【LeetCode】217 & 219 - Contains Duplicate & Contains Duplicate II
217 - Contains Duplicate Given an array of integers, find if the array contains any duplicates. You ...
- [Leetcode] Remove duplicate from sorted list ii 从已排序的链表中删除重复结点
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numb ...
- 【leetcode❤python】 219. Contains Duplicate II
#-*- coding: UTF-8 -*-#遍历所有元素,将元素值当做键.元素下标当做值#存放在一个字典中.遍历的时候,#如果发现重复元素,则比较其下标的差值是否小于k,#如果小于则可直接返回Tru ...
- LeetCode(219) Contains Duplicate II
题目 Given an array of integers and an integer k, find out whether there are two distinct indices i an ...
- LeetCode Array Easy 219. Contains Duplicate II
---恢复内容开始--- Description Given an array of integers and an integer k, find out whether there are two ...
随机推荐
- Leetcode#89 Gray Code
原题地址 二进制码 -> 格雷码:从最右边起,依次与左边相邻位异或,最左边一位不变.例如: 二进制: 1 0 0 1 1 1 0 |\|\|\|\|\|\| 格雷码: 1 1 0 1 0 0 1 ...
- NSStream
NSStream 流是位数据通过通信路径的连续传送序列.它是单向的,从一个应用程序的角度,流可以是输入流(读操作流)或者输出流(写操作流),除了基于文件的流之外,其余的都是non-seekable的. ...
- [错误代码:0x80070002]IIS7及以上伪静态报错404
故障现象:DTCMS开启伪静态功能,VS2010预览正常,发布到IIS后报错404.0错误 (WIN7,WIN8,SERVER2008).模块IISWebCore通知MapRequestHandler ...
- Centos最小化安装后联网配置
Centos最小化安装默认不开启网络,只需进行简单配置就可以上网了. 1. 查看/etc/sysconfig/network-scripts/下面的文件,这里会有一个ifcfg-en******(这 ...
- Unity Texture 2D Compress
测试了一下 unity 图片 对 apk 的影响. 上两种测试环境 1024 * 1024 带 alpha的话 默认压缩就是RBA 16bit就是2M 不带的话就是 etc 的话 ...
- ErrorCode枚举类型返回错误码信息测试,手动抛出异常信息,在事务中根据错误码来回滚事务的思路。
ErrorCode.java 简单测试代码,具体应用思路:手动抛出异常信息,在事务中根据错误码来回滚事务的思路. public enum ErrorCode { //系统级 SUCCESS(" ...
- 斌哥的 Docker 进阶指南—监控方案的实现
过去的一年中,关于 Docker 的话题从未断过,而如今,从尝试 Docker 到最终决定使用 Docker 的转化率依然在逐步升高,关于 Docker 的讨论更是有增无减.另一方面,大家的注意力也渐 ...
- 【译】 沙箱中的间谍 - 可行的 JavaScript 高速缓存区攻击
王龑 - MAY 27, 2015 原文连接 The Spy in the Sandbox – Practical Cache Attacks in Javascript 相关论文可在 https:/ ...
- 由浅入深了解Thrift之微服务化应用架构
为什么选择微服务 一般情况下,业务应用我们都会采用模块化的分层式架构,所有的业务逻辑代码最终会在一个代码库中并统一部署,我们称这种应用架构为单体应用. 单体应用的问题是,全部开发人员会共享一个代码库, ...
- ios图片拉伸两种方法
UIImage *image = [UIImage imageNamed:@"qq"]; 第一种: // 左端盖宽度 NSInteger leftCapWidth = image. ...