码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode]Contains Duplicate II解题报告 C语言

时间:2015-08-28 17:45:11      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:c语言   leetcode   

【题目】
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个数比较。如果相等,则返回true。当数组遍历完之后,没有发现满足条件的。返回false。
【具体代码如下】

bool containsNearbyDuplicate(int* nums, int numsSize, int k) {
      int i;
      int j;
      if(numsSize==1)return false;
      for(i=0;i<numsSize-1;i++)
      {
        for(j=i+1;(j<=i+k)&&(j<numsSize);j++)
        {
            if(nums[i]==nums[j])
            return true;
          }
      }
      return false;

}

【个人总结】
有两个地方需要注意:
1.当numsSize为1的时候,则说明只有一个数,直接返回false.
2.第2个for循环的终止条件判断时,j

版权声明:本文为博主原创文章,未经博主允许不得转载。

[leetcode]Contains Duplicate II解题报告 C语言

标签:c语言   leetcode   

原文地址:http://blog.csdn.net/noc_lemontree/article/details/48053643

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