首页 > 其他 > 详细

Contain Duplicate II

时间:2015-08-19 07:01:33      阅读:110      评论:0      收藏:0      [点我收藏+]

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

 

Analyse: 

1. For every element in the array, find if other elements meet its requirement.

    Time Limited Exceeded.

技术分享
 1 class Solution {
 2 public:
 3     bool containsNearbyDuplicate(vector<int>& nums, int k) {
 4         if(nums.size() <= 1) return 0 <= k;
 5         
 6         for(int i = 0; i < nums.size(); i++){
 7             for(int j = i + 1; j <= i + k; j++){
 8                 if(nums[j] == nums[i]) return true;
 9             }
10         }
11         return false;
12     }
13 };
View Code

2. As long as one of the element in the remaining part satisfy the condition, we can return true.

    Runtime: 32ms.

 1 class Solution {
 2 public:
 3     bool containsNearbyDuplicate(vector<int>& nums, int k) {
 4         unordered_map<int, int> up;
 5         for(int i = 0; i < nums.size(); i++){
 6             if(up.find(nums[i]) != up.end() && i - up.find(nums[i])->second <= k) return true;
 7             else up[nums[i]] = i;
 8         }
 9         return false;
10     }
11 };

 

Contain Duplicate II

原文:http://www.cnblogs.com/amazingzoe/p/4741155.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!