<leetcode系列> Contains Duplicate II
2015-09-22 23:27
369 查看
Contains Duplicate II
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 j is at most k.题意如下:
给定整数数组nums和整数k, 判断在数组中是否存在nums[i] = nums[j], 并且i, j满足i, j之差不大于k.
和Contains Duplicate I 和类似之处.代码中也用到了Contains Duplicate I的代码.
题目链接: https://leetcode.com/problems/contains-duplicate-ii/
Contains Duplicate I 链接: https://leetcode.com/problems/contains-duplicate/
由于很少使用标准库中的各种数据结果,如vector, map等,对于string这种类型,其中的各种成员函数都要先百度,才只有有什么可以调用,不同库中的string又有不小的差异.故我选用的是C语言.代码如下:
// 在长度为numsSize的数组nums中,是否包含相同的数.utils是为了避免重复申请工具数组. bool containsDuplicate(int* nums, int numsSize, int* utils) { if ((0 >= numsSize) || (NULL == nums)) { return false; } for (int i = 0; i < numsSize; ++i) { ++utils[nums[i]]; if (utils[nums[i]] > 1) { return true; } } return false; } bool containsNearbyDuplicate(int* nums, int numsSize, int k) { if ((NULL == nums) || (1 >= numsSize) || (0 >= k)) { return false; } int maxVal = -2147483648; int minVal = 2147483647; for (int i = 0; i < numsSize; ++i) { if (maxVal < nums[i]) { maxVal = nums[i]; } if (minVal > nums[i]) { minVal = nums[i]; } } for (int i = 0; i < numsSize; ++i) { nums[i] -= minVal; } maxVal -= minVal; if (maxVal == 0) { // 正常情况下,maxVal应该是大于等于0的.如果等于零, 则所有数相等 return true; } // 索引到下标maxVal, 则需要maxVal + 1长度的数组 int* utils = (int*) malloc((maxVal + 1) * sizeof(int)); memset(utils, '\0', (maxVal + 1) * sizeof(int)); bool ret = false; if (k >= numsSize) { ret = containsDuplicate(nums, numsSize, utils); } else { for (int i = 0; i < numsSize - k; ++i) { if (containsDuplicate(nums + i, k + 1, utils)) { ret = true; break; } memset(utils, '\0', (maxVal + 1) * sizeof(int)); } } free(utils); utils = NULL; return ret; }
相关文章推荐
- Know more about RAC statistics and wait event
- hdoj4720Naive and Silly Muggles【求外接圆圆心】
- main 函数自身递归调用+感想
- SSH 整合的时候遇到的问题 Failed to read candidate component class
- LeetCode(37) Contain Duplicates I II
- android.intent.category.LAUNCHER 和 android:name="android.intent.action.MAIN 的作用
- Uva 514 Rails
- [MFC]CView视图类、CMainFrame主框架类
- hdu 2389 Rain on your Parade【最大匹配】
- HDOJ 2057 A + B Again (十六进制)
- HDU_3376_Matrix Again(最小费用流)
- 03-树3 Tree Traversals Again
- NSSearchPathForDirectoriesInDomains用法
- _exit和exit的区别 http://www.cnblogs.com/hnrainll/archive/2011/08/17/2142001.html
- wait和waitpid函数
- 微博情感分析的表情符号平滑语言模型(A11, AAAI2012)
- Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING
- rhel6安装aircrack-ng
- Unity 3D 使用TerrainCompose 调用RTP 报错:
- weglogic Error 503--Service Unavailable