LeetCode:219. Contains Duplicate II
2016-01-10 10:52
555 查看
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 jis
at most k.
查找数组中的是否有重复元素,并且要求查找半径小于等于k的值,设定两个指针就好,start 和end,具体实现看代码:
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 jis
at most k.
查找数组中的是否有重复元素,并且要求查找半径小于等于k的值,设定两个指针就好,start 和end,具体实现看代码:
import java.util.HashSet; import java.util.Set; /** * Created by jason on 2016/1/10. */ class Solution39 { Set<Integer> apperNum = new HashSet<Integer>(); public boolean containsNearbyDuplicate(int[] nums, int k) { int start=0,end =0; if (nums == null || nums.length <0) {return false;} for (int i=0; i<nums.length; i++) { if(!apperNum.contains(nums[i])) { apperNum.add(nums[i]); end++; }else { return true; } if (end - start > k) { apperNum.remove(nums[start]); start++; } } return false; } } public class LC39 { public static void main(String[] ars) { Solution39 solution39 = new Solution39(); int[] nums = new int[]{2, 3, 2, 5}; if (solution39.containsNearbyDuplicate(nums, 1)) { System.out.println("true"); }else { System.out.println("false"); } } }
相关文章推荐
- c++ 友元函数 还是不能访问私有成员。。 http://zhidao.baidu.com/link?url=Ccm5gZvOc733A_YsS2kj-LZsVtdwu6BT3WR97u66jZAZ1
- Android USB Connections Explained: MTP, PTP, and USB Mass Storage
- 安卓学习-谷歌官方文档翻译01-Training-GettingStarted
- LeetCode OJ - Container With Most Water
- <LeetCode OJ> 219. Contains Duplicate II
- Codeforces 615B Longtail Hedgehog (Round #338 (Div. 2) B题)
- Codeforces Round #338 (Div. 2) B. Longtail Hedgehog DP
- int main(int argc,char* argv[])详解
- clang: error: linker command failed with exit code 1 (use -v to see invocation)错误问题
- Codeforces Round #338 (Div. 2) B. Longtail Hedgehog(LIS)
- Codeforces Round #335 (Div. 2) C. Sorting Railway Cars
- AI学习笔记和制作棋子的教程
- [leetcode oj 217]Contains Duplicate
- Codeforces Round #338 (Div. 2) 615B Longtail Hedgehog(dp)
- Codeforces 615C:Longtail Hedgehog
- main函数的autoreleasepool有何用处
- LightOJ1021 Painful Bases(状压DP)
- 异步AIO的研究
- scu - 3254 - Rain and Fgj(最小点权割)
- 蓝牙写入出错,error isError Domain=CBATTErrorDomain Code=114 "Unknown ATT error."