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 ...
随机推荐
- 剑指offer--面试题21--相关
题目:设计包含min函数的栈,pop(),push(),min()的时间复杂度均为O(1) 自己所写代码如下:(写‘栈’的代码还是有些不熟练!) #include <iostream> u ...
- ios读取通讯录信息
ios读取通讯录信息 (2012-05-22 14:07:11) 标签: ios读取通讯录 it iphone如许app读取通讯录信息,读取通讯录信息时需要加载AddressBookUI 和Add ...
- json_encode charset
json_encode utf-8 mysql charset utf8
- no module named staticfiles
原地址:http://blog.sina.com.cn/s/blog_77500e110100umms.html 今天想试一下django的Uploadify,找了个例子,运行时出错:myprojec ...
- 翻译 - NodeJS错误处理最佳实践
王龑 - APRIL 13, 2015 NodeJS的错误处理让人痛苦,在很长的一段时间里,大量的错误被放任不管.但是要想建立一个健壮的Node.js程序就必须正确的处理这些错误,而且这并不难学.如果 ...
- Activity学习(三)——跳转传值
Activity跳转与传值,主要是通过Intent类来连接多个Activity,以及传递数据. Intent是Android一个很重要的类.Intent直译是“意图”,什么是意图呢?比如你想从这个 ...
- Javascript 图片延迟加载之理论基础
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...
- 2016PHP开发者大会
大会干货: Rasmus Lerdorf——<Speeding up the Web with PHP 7> PHP 7 is here. It brings drastic perfor ...
- http://jingyan.baidu.com/article/d169e186b38c37436611d8fa.html
http://jingyan.baidu.com/article/d169e186b38c37436611d8fa.html
- grep是模糊匹配
1. 我:我用的ps -nat|grep -i "80"|wc -l命令 我:解释详细点,,龙哥,对于我这种菜鸟:也是模糊匹配 :你用 grep "80" 会匹 ...