标签:contains duplicate leetcode
主要是寻找数组中是否有相等数字的题目
在前面已经有一道题目,没有记录是数组中都是两个的数字,选择一个只有一个出现的数字,最简单的方法就是将所有的数字进行异或的过程,最后剩下的情况就是需要求的数据
下面的三个题目都是和数组有关的,自己有的最多的方法就是使用set和map进行记录的过程
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.
https://leetcode.com/problems/contains-duplicate/
class Solution { public: bool containsDuplicate(vector<int>& nums) { if(nums.empty()) { return false; } set<int> numSet; set<int> twiceNumSet; for(int i = 0; i < nums.size(); i++) { if(!(numSet.count(nums[i]))) { if(!(twiceNumSet.count(nums[i]))) { numSet.insert(nums[i]); } else { return true; } } else { return true; } } return false; } };Contains Duplicate II
Given an array of integers and an integer k, find out whether 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.
找到两个相等的数字之间索引下表差距最多为 k
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { map<int, int> buf; int n = nums.size(); for (int i = 0; i < n; i++) { if (buf.count(nums[i]) && i-buf[nums[i]] <= k) { return true; } else { buf[nums[i]] = i; } } return false; } };
public class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { //0842 Set<Integer> appearedNum = new HashSet<Integer>(); int start = 0, end = 0; for(int i = 0; i < nums.length; i++){ if(!appearedNum.contains(nums[i])){ appearedNum.add(nums[i]); end++; } else return true; if(end - start > k) { appearedNum.remove(nums[start]); start++; } } return false; //0848 } }
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.
这里是需要在数组中寻找合适的两个元素
最简单的方式就是维持一个窗口,移动star,end两个元素,然后内部利用一个二维遍历,可以完成相应的比较的过程,但是费时
因为这里涉及到数据大小的比较,会想到BST,如果自己维持一个k大小的树,来一个元素比较的时候就可以直接根据和根节点相比较的过程进行判断。
可以自己进行维护
在stl中,set和map底层都是红黑树,可以自己直接利用lower_bond和upper_bond找到最接近需要判断的数据的树
class Solution { public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { multiset<long long> bst; for (int i = 0; i < nums.size(); ++i) { if (bst.size() == k + 1) bst.erase(bst.find(nums[i - k - 1])); auto lb = bst.lower_bound(nums[i] - t); if (lb != bst.end() && *lb - nums[i] <= t) return true; bst.insert(nums[i]); } return false; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:contains duplicate leetcode
原文地址:http://blog.csdn.net/xietingcandice/article/details/48088877