leetcode 287. Find the Duplicate Number 数组重复元素查询 + 环的存在判定 + 快慢指针 + 很妙的想法
2017-09-28 09:47
591 查看
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.
因为数组的内容和下标范围是一致的,所以可以考虑作为一个链表来做,我在网上看到了一个使用类似快慢指针的做法去做,想法很棒。
不过最最直接的方法还是使用HashMap来完成计数。
代码如下:
下面是C++的做法,就是使用双指针做一个遍历,注意这个题很巧妙,可以使用双指针来做。
代码如下:
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.
因为数组的内容和下标范围是一致的,所以可以考虑作为一个链表来做,我在网上看到了一个使用类似快慢指针的做法去做,想法很棒。
不过最最直接的方法还是使用HashMap来完成计数。
代码如下:
/* * https://discuss.leetcode.com/topic/25685/java-o-n-time-and-o-1-space-solution-similar-to-find-loop-in-linkedlist * * 这个题很巧,可以利用寻找链表是否存在环的方法判断 * 技巧性很强,需要好好想一下 * */ class Solution { public int findDuplicate(int[] nums) { if(nums==null || nums.length<=1) return 0; int slow=nums[0]; int fast=nums[nums[0]]; while(fast!=slow) { slow=nums[slow]; fast=nums[nums[fast]]; } slow=0; while(fast!=slow) { slow=nums[slow]; fast=nums[fast]; } return slow; } }
下面是C++的做法,就是使用双指针做一个遍历,注意这个题很巧妙,可以使用双指针来做。
代码如下:
#include <iostream> #include <vector> #include <map> #include <set> #include <queue> #include <stack> #include <string> #include <climits> #include <algorithm> #include <sstream> using namespace std; class Solution { public: int findDuplicate(vector<int>& a) { int slow = a[0]; int fast = a[slow]; while (fast != slow) { slow = a[slow]; fast = a[a[fast]]; } slow = 0; while (fast != slow) { slow = a[slow]; fast = a[fast]; } return fast; } };
相关文章推荐
- leetcode 26. Remove Duplicates from Sorted Array从排序数组中移出重复元素(双指针)
- 如何判定数组是否存在重复元素
- 判定数组中是否存在重复元素
- 假设数组a有n个元素,元素取值范围是1~n,如何判定数组是否存在重复元素
- leetcode 4. 移除有序数组中的重复元素 Remove Duplicates from Sorted Array
- javascript 校验字符串(数字)数组是否存在重复元素
- 【LeetCode-面试算法经典-Java实现】【026-Remove Duplicates from Sorted Array(删除排序数组中的重复元素)】
- 【Leetcode】从排序数组中删除重复元素
- 哈希(6) - 判断数组中是否存在重复元素且距离在K之内
- 判断数组中是否存在重复的元素
- [LeetCode-26] Remove Duplicates from Sorted Array(移除数组重复元素)
- leetcode 题解:Remove Duplicates from Sorted Array II(已排序数组去三次及以上重复元素)
- 程序员面试题目总结--数组(四)【数列中符合条件数对的个数、数组是否存在重复元素、重新排列数组使数组左边为奇数,右边为偶数、数组中的第二大数、数组中的最小值和最大值】
- LeetCode 26. Remove Duplicates from Sorted Array(移除有序数组的重复元素)
- 每天一道LeetCode-----有序数组循环右移n位后,寻找最小值,数组中可能包含重复元素
- Leetcode442. 通过哈希表找出数组重复元素
- Leetcode:219. Contains Duplicate II(数组是否含有重复元素)
- leetcode:Remove Duplicates from Sorted Array去掉排序数组中重复的元素
- java判定数组或集合是否存在某个元素
- 取值为[1,n-1] 含n 个元素的整数数组至少存在一个重复数,O(n) 时间内找出其中任意一个重复数