LeetCode219题:Contains Duplicate II
2016-03-04 19:14
423 查看
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.
问题需求:
给与一个整型数组,同时给于一个整数k,寻找该数组是否有两个相等的数,且这两个数之间间隔的数字个数小于k个,即nums[i]==nums[j],且i与j之差的绝对值不大于k。
问题分析:
两数相等,且两个数之间间隔数字个数少于k个,等价于,对给定的第i个数字,在偏移量i+k的范围内,是否能够找到一个数其数值等于第i个数,当i从零一直到数组的末尾(即遍历完整个数组)都没找到,则不存在,如对于任意有效的i,在i+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.
问题需求:
给与一个整型数组,同时给于一个整数k,寻找该数组是否有两个相等的数,且这两个数之间间隔的数字个数小于k个,即nums[i]==nums[j],且i与j之差的绝对值不大于k。
问题分析:
两数相等,且两个数之间间隔数字个数少于k个,等价于,对给定的第i个数字,在偏移量i+k的范围内,是否能够找到一个数其数值等于第i个数,当i从零一直到数组的末尾(即遍历完整个数组)都没找到,则不存在,如对于任意有效的i,在i+k的范围内,能够找到相等的数,就是存在。
bool containsNearbyDuplicate(int* nums, int numsSize, int k) { int currentPosition; int point; //遍历数组每轮确定一个位置上面的数是否满足要求 for(currentPosition = 0;currentPosition<numsSize;currentPosition++){ // 注意这里循环条件,首先要在有效范围之内,其次偏移量不可以超出数组长度 for(point = currentPosition+1;point-currentPosition<=k && point<numsSize;point++){ // 如果任意位置有符合条件的数据 if(nums[currentPosition]==nums[point]){ return 1; } } } return 0;//如果一直没有符合条件的数则返回零 }
相关文章推荐
- 【GDKOI2016】魔卡少女Code&&Details
- http://blog.csdn.net/luxiaoyu_sdc/article/details/7333024
- HDU 2674 N!Again [Ad Hoc]
- retain、strong、weak、assign区别
- Git配置全局和独立仓库的username和email配置
- 进阶篇:以IL为剑,直指async/await
- 使用WebDriverWait类处理等待(sleep)的问题
- HDOJ-1789 Doing Homework again
- 使用AFN 的POST请求出现错误"Error Domain=NSCocoaErrorDomain Code=3840 "决绝方案
- HDU 3356 ||POJ 3996Air Strike(贪心)
- hdu 4630 No Pain No Game 线段树离线处理
- pthread_cond_wait()与pthread_cond_signal()
- quartz报错:SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-op
- Forcing the Removal of a Domain Controller
- Thread 常搞混的几个概念sleep、wait、yield、interrupt
- 打造你的办公环境-email篇
- 【什么是长尾关键词(Long Tail Keyword)】
- 在mac上用Xcode写程序, run的时候总是失败, 显示clang: error: linker command failed with exit code 1
- How To Reclaim Wasted Space on The Segment (Table, Index and LOB) and Tablespace Levels (文档 ID 16827
- 怎样用好ZBrush中的PaintStop插件