Contains Duplicate II
来源:互联网 发布:淘宝商品包装怎么设置 编辑:程序博客网 时间:2024/05/17 02:41
开始题目都没读懂。是求数列中,是否存在两个相同元素且距离不超过k。这道题比I式稍难,因为要全部遍历而且用例有负数。我的思路是用了个二维数组来分别存正数index和负数index,至于求最小距离的话只需要设置一个gap变量保存前一次该数的index与当次index之差,如果差值小于上一次所求的差值,就更新gap和哈希表里的index。思路很朴素用了快50行而且判断不少,说明逻辑写得不好。今后会网搜下其他答案吸收精华。
如下:
bool containsNearbyDuplicate(int* nums, int numsSize, int k) { bool result = false; bool isIn = false; int row = 2, column = 102400; int hashtable[row][column]; memset(hashtable[0], -1, sizeof(int) * column); memset(hashtable[1], -1, sizeof(int) * column); int temp = 0; int low = -1, high = -1; int gap = 1024; for (int i = 0; i < numsSize; i++) { if (nums[i] < 0) { temp = -nums[i]; if (hashtable[1][temp] == -1) { hashtable[1][temp] = i; } else { low = hashtable[1][temp]; if (i - low <= gap) { gap = i - low; high = i; hashtable[1][temp] = i; isIn = true; } } } else { temp = nums[i]; if (hashtable[0][temp] == -1) { hashtable[0][temp] = i; } else { low = hashtable[0][temp]; if (i - low <= gap) { gap = i - low; high = i; hashtable[0][temp] = i; isIn = true; } } } } if (low < 0) low = hashtable[1][high]; if (high - low <= k && isIn) result = true; return result;}
0 0
- Contains Duplicate && Contains Duplicate II
- [LeetCode]Contains Duplicate II
- Contains Duplicate II
- [LeetCode] Contains Duplicate II
- leetcode Contains Duplicate II
- LeetCode Contains Duplicate II
- [leetcode] Contains Duplicate II
- LeetCode Contains Duplicate II
- LeetCode219:Contains Duplicate II
- #219 Contains Duplicate II
- 219. Contains Duplicate II
- 【leetcode】Contains Duplicate II
- leetcode--Contains Duplicate II
- 219Contains Duplicate II
- Contains Duplicate II
- Contains Duplicate II
- Contains Duplicate II
- Leetcode_219 Contains Duplicate II
- Linux C 编程内存泄露检测工具:memwatch
- JQuery学习系列1
- 分析开源三大CMS中WordPress相比Drupal与Joomla是怎样摘取皇冠的
- 手动触发js事件
- Android相关网站
- Contains Duplicate II
- 水泵用的压力开关
- Quartz作业调度框架
- Mac 常用命令
- JQuery中$.ajax()方法参数详解
- android 广播详解
- Maven学习
- 图像的腐蚀和膨胀------学习记录(9)
- Android Drawable