【leetcode】Contains Duplicate I && II
2015-05-29 16:46
701 查看
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.
II:
Given an array of integers and an integer k,
return true if and only if there are two distinct indices i and j in the array such that nums[i] = nums[j]
and the difference between i and j is at most k.
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.
class Solution { public: bool containsDuplicate(vector<int>& nums) { if(nums.size()==0) return false; sort(nums.begin(),nums.end()); int tmp=nums[0]; for(int i=1;i<nums.size();i++) { if(nums[i]==tmp) return true; else tmp=nums[i]; } return false; } };
II:
Given an array of integers and an integer k,
return true if and only if there are two distinct indices i and j in the array such that nums[i] = nums[j]
and the difference between i and j is at most k.
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { if(nums.size()==0) return false; //if(k>nums.size()) return false; map<int,int> tmp; for(int i=0;i<nums.size();i++) { if(tmp.find(nums[i])!=tmp.end()&&i-tmp[nums[i]]<=k) { return true; }else { tmp[nums[i]]=i; } } return false; } };
相关文章推荐
- Host key verification failed解决
- NBUT 1118 Marisa's Affair (排序统计,水)
- 基于wait和notify的生产者消费者实例
- Contains Duplicate II
- [AIX] ksh中的命令行编辑
- leetcode 219: Contains Duplicate II
- Common realloc mistake: 'd_data' nulled but not freed upon failure
- [LeetCode] Contains Duplicate & Contains Duplicate II
- 5分钟学会AIDL
- [LeetCode]Contains Duplicate II
- Minimum Average Waiting Time
- make_pair
- golang 的 sync.WaitGroup
- 捕获fail2ban截获的Ip写入拒绝主机列表
- ArtifactTransferException: Failure to transfer xalan:xalan:jar:2.6.0 from http://repo.maven.apache.o
- AIX telnet: connect: Cannot reach the destination network.
- DNA repair问题
- SSH远程连接报错:Could not connect to '10.43.2.113' (port 22): Connection failed.
- leetcode--Contains Duplicate
- Postfix maillog邮件发送各阶段延时的日志记录