[LeetCode] Contains Duplicate(II,III)

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.

解题思路

用一个set保存数组中的值,如果发现当前值已经在set中存在,则返回true。

实现代码

// Rumtime: 67 ms
class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        set<int> s;
        for (int i = 0; i < nums.size(); i++)
        {
            if (s.insert(nums[i]).second == false)
            {
                return true;
            }
        }

        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 i and j is at most k.

解题思路

用map存储数组元素和下标,看是否存在与当前元素相等且下标之差小于等于k的元素,存在则返回true;否则将当前元素和其下标存入map。

实现代码

// Runtime: 76 ms
class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        map<int, int> mymap;
        for (int i = 0; i < nums.size(); i++)
        {
            if (mymap.find(nums[i]) != mymap.end() && i - mymap[nums[i]] <= k)
            {
                return true;
            }
            else
            {
                mymap[nums[i]] = i;
            }
        }

        return false;
    }
};

Contains Duplicate III

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.

解题思路

用一个multiset存储数组中的元素,保持multiset中元素个数为k,这样multiset中元素与当前元素num[i]的下标之差均小于等于k。iterator lower_bound (const value_type& val) const可以用于返回值小于等于val的元素的迭代器,判断返回迭代器所指向的值与当前元素之差是否小于等于t即可。

实现代码

// Runtime: 44 ms
class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        multiset<int> s;
        for (int i = 0; i < nums.size(); i++)
        {
            if (s.size() == k + 1)
            {
                s.erase(s.find(nums[i-k-1]));
            }
            auto it = s.lower_bound(nums[i] - t);
            if (it != s.end())
            {
                int diff = nums[i] > *it ? nums[i] - *it : *it - nums[i];
                if (diff <= t)
                {
                    return true;
                }
            }

            s.insert(nums[i]);
        }

        return false;
    }
};
时间: 2024-10-15 02:57:02

[LeetCode] Contains Duplicate(II,III)的相关文章

[LeetCode] My Calendar II 我的日历之二

Implement a MyCalendarTwo class to store your events. A new event can be added if adding the event will not cause a triple booking. Your class will have one method, book(int start, int end). Formally, this represents a booking on the half open interv

[LeetCode] Sentence Similarity II 句子相似度之二

Given two sentences words1, words2 (each represented as an array of strings), and a list of similar word pairs pairs, determine if two sentences are similar. For example, words1 = ["great", "acting", "skills"] and words2 = [&

[LeetCode] Bulb Switcher II 灯泡开关之二

There is a room with n lights which are turned on initially and 4 buttons on the wall. After performing exactly m unknown operations towards buttons, you need to return how many different kinds of status of the n lights could be. Suppose n lights are

[LeetCode] Valid Palindrome II 验证回文字符串之二

Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. Example 1: Input: "aba" Output: True Example 2: Input: "abca" Output: True Explanation: You could delete the character 'c'. N

[LeetCode] Beautiful Arrangement II 优美排列之二

Given two integers n and k, you need to construct a list which contains n different positive integers ranging from 1 to n and obeys the following requirement:  Suppose this list is [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4

[LeetCode] Find Duplicate Subtrees 寻找重复树

Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any oneof them. Two trees are duplicate if they have the same structure with same node values. Example 1:  1 / \ 2 3 / /

[LeetCode] Decode Ways II 解码方法之二

A message containing letters from A-Z is being encoded to numbers using the following mapping way: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Beyond that, now the encoded string can also contain the character '*', which can be treated as one of the numbers

[LeetCode]--219. 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的滑动窗口,用一个set维护窗口内的数字判断是否出现重复,使用两个指针

[LeetCode]90.Subsets II

题目 Given a collection of integers that might contain duplicates, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,2], a solution