码迷,mamicode.com
首页 > 其他好文 > 详细

LeeCode题目总结(1)

时间:2015-05-31 12:13:16      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

Contain 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.

代码:

 1 public class Solution {
 2     public boolean containsNearbyDuplicate(int[] nums, int k) {
 3         boolean tag = false; // 设置标志位
 4         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
 5 
 6         if (nums.length <2 || k == 0) {
 7             return tag;
 8         }
 9         for (int i = 0; i < nums.length; i++) {
10 
11             // 如果在map中找到num[i],那么开始判断
12             if (map.containsKey(nums[i])) {
13                 int index = map.get(nums[i]);
14                 if ((i-index) <= k) {
15                     tag = true;
16                 }
17             }
18             // 如果在map中找不到,那么就将该值放入map之中
19             map.put(nums[i], i);
20         }
21         return tag;
22     }
23 }

我做看到这道题目的时候,第一反应就是使用两个for循环,一个用于遍历数组并将数组中的元素保存在一个变量中,另一个数组用于将数组中的其他元素分别和第一个for中的变量进行比较,但按照这个思路编写好的程序执行效率特别低。提交代码的时候,就报了time limited错误。

所以可以使用map集合进行数据的存储,但关键是map<key,value>中都保存那些内容,在该题中一反常态,将数组中的值保存在key中,将数组的下标保存在value中。当数组中出现重复的元素时,外部循环中的i代表了该重复元素在数组中的位置,map.get(num[i])表示该元素第一次出现在map中的位置,这样问题就解决了。

LeeCode题目总结(1)

标签:

原文地址:http://www.cnblogs.com/ouwenkgwpf/p/4541641.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!