Duplicate element 219. II - stay button (LeetCode)

Title Description

给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 ij 的差的绝对值最大为 k

Example 1:

Input: the nums = [1,2,3,1], K  =. 3
 Output: to true

Example 2:

Input: the nums = [1,0,1,1], K  =  . 1
 Output: to true

Example 3:

Input: the nums = [1,2,3,1,2,3], K  =  2
 Output: to false

Problem solution 1

At first wrong topic, the "maximum" word missing. The method is then determined by the difference between the force of the two numbers in the subscript k ranges are equal, timeout ! !

Code 1

/*
暴力方法,时间复杂度为O(n^2)
*/
class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        int len = nums.size();//长度
        bool flag = false;
        for(int i = 0; i < len; ++i){
            if(!flag){
                for(int j = i + 1; j <= i + k && j < len; ++j){
                    if(nums[i] == nums[j]){
                        flag = true;
                        break;
                    }
                }
            }
        }
        return flag;
    }
};

2 solution to a problem

Since determine whether two numbers are equal, there is to find. If the use of set and map these data structures, certainly much faster speed.
Specific ideas are: the establishment of a map, key elements for the value, value for the index. Traversing nums array elements is determined whether the map in the presence, absence, was added. Exist, to determine whether the difference between the index not greater than k, greater than, the current element value is updated to a larger index, otherwise, the two elements are found eligible, returns true.
·

Code 2

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        int len = nums.size();//长度
        bool flag = false;
        map<int, int>myMap;
        for(int i = 0; i < len; ++i){
            if(myMap.find(nums[i]) ==myMap.end()){//不存在
                myMap[nums[i]] = i;
            }
            else{
                int j = myMap[nums[i]];
                if(i - j <= k){//符合条件
                    flag = true;
                    break;
                }
                else{//不符合,更新下标为较大值
                    myMap[nums[i]] = i;
                }
            }
        }
        return flag;
    }
};

Execution result 2

Here Insert Picture Description

Published 152 original articles · won praise 29 · views 40000 +

Guess you like

Origin blog.csdn.net/happyeveryday62/article/details/104112812