LeetCode 287
2016-05-20 12:55
423 查看
Find the Duplicate Number
Given an array nums containing n + 1 integers where
each integer is between 1 and n (inclusive),
prove that at least one duplicate number must exist.
Assume that there is only one duplicate number, find the duplicate one.
Note:
You must not modify the array (assume the array is read only).
You must use only constant, O(1) extra space.
Your runtime complexity should be less than O(n2).
There is only one duplicate number in the array,
but it could be repeated more than once.
Given an array nums containing n + 1 integers where
each integer is between 1 and n (inclusive),
prove that at least one duplicate number must exist.
Assume that there is only one duplicate number, find the duplicate one.
Note:
You must not modify the array (assume the array is read only).
You must use only constant, O(1) extra space.
Your runtime complexity should be less than O(n2).
There is only one duplicate number in the array,
but it could be repeated more than once.
/************************************************************************* > File Name: LeetCode287.c > Author: Juntaran > Mail: JuntaranMail@gmail.com > Created Time: Tue 17 May 2016 20:20:12 PM CST ************************************************************************/ /************************************************************************* Find the Duplicate Number Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. Note: You must not modify the array (assume the array is read only). You must use only constant, O(1) extra space. Your runtime complexity should be less than O(n2). There is only one duplicate number in the array, but it could be repeated more than once. ************************************************************************/ #include <stdio.h> int findDuplicate(int* nums, int numsSize) { if(numsSize > 0) { int slow = nums[0]; int fast = nums[nums[0]]; while(slow != fast) //check the existence of the loop; { printf("%d %d\n", slow, fast); slow = nums[slow]; fast = nums[nums[fast]]; } printf("%d %d\n", slow, fast); fast = 0; while(slow != fast) //find the start of the loop which means at least two integer are the same value; { slow = nums[slow]; fast = nums[fast]; } return slow; } return -1; } int main() { int nums[] = {1,3,4,2,2}; int numsSize = 5; int ret = findDuplicate( nums, numsSize); printf("%d\n", ret); }
相关文章推荐
- 运维审计系统
- LeetCode 278
- LeetCode 274
- 各类编程软件安装配置流程
- 获取系统表和字段
- 手把手教程 Surface如何进行系统恢复?
- 坐标距离算法
- 网络流二十四题之十九 —— 负载平衡问题
- Android 史上最简单的实现Canvas drawText文字垂直居中
- Andriod开发环境搭建
- LeetCode 264
- 程序启动 - 类调用的方法
- 平日小问题(3):分数的求和问题
- [记忆向]工作中一些实用的Linux命令组合(持续)
- Discuz X3.2插件开发(一)
- RecyclerView学习(二)----高仿网易新闻栏目动画效果
- SPOJ_10628_Count_on_a_Tree_(主席树+Tarjan)
- LeetCode 206
- LeetCode 189
- Unity 基础 - Transform