287. Find the Duplicate Number
来源:互联网 发布:网易对战平台mac版 编辑:程序博客网 时间:2024/05/16 17:31
题目
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
暴力解法
public class Solution { // 暴力搜索法 public int findDuplicate(int[] nums) { int res = 0; for(int num : nums){ int time = 0; for(int n : nums){ if(num == n) time++; } if(time >= 2){ res = num; break; } } return res; }}分析:统计每一个数字出现的次数,找到重复的数字。时间复杂度O(n^2)
二分法:
public class Solution { public int findDuplicate(int[] nums) { int min = 0, max = nums.length - 1; while(min <= max){ // 找到中间那个数 int mid = min + (max - min) / 2; int cnt = 0; // 计算总数组中有多少个数小于等于中间数 for(int i = 0; i < nums.length; i++){ if(nums[i] <= mid){ cnt++; } } // 如果小于等于中间数的数量大于中间数,说明前半部分必有重复 if(cnt > mid){ max = mid - 1; // 否则后半部分必有重复 } else { min = mid + 1; } } return min; }}
映射找环法(不理解)
传送门
0 0
- 287. Find the Duplicate Number
- 287. Find the Duplicate Number
- 287. Find the Duplicate Number
- 287. Find the Duplicate Number
- 287. Find the Duplicate Number
- 287. Find the Duplicate Number
- 287. Find the Duplicate Number
- 287. Find the Duplicate Number
- 287. Find the Duplicate Number
- 287. Find the Duplicate Number
- 287.Find the Duplicate Number
- 287. Find the Duplicate Number
- 287. Find the Duplicate Number
- 287. Find the Duplicate Number
- 287. Find the Duplicate Number
- 287. Find the Duplicate Number
- 287. Find the Duplicate Number
- 287. Find the Duplicate Number
- 针对eclipse安装spring插件安装失败或者后不显示spring文件或者的解决办法
- 1041. Be Unique (20)
- win10 64位+qwt 6.1.4+qt 5.8.0 msvc2015 x64安装方法
- 67.protobuf入门
- C++ map的遍历
- 287. Find the Duplicate Number
- 机器学习玩家必收——常用N大算法
- Sharding模式
- (七)计算器实例
- poj 2115 C Looooops
- 十二、java中的抽象类
- LEETCODE--Number of Boomerangs
- Lottie开源动画库使用教程
- 一文读懂机器学习,大数据/自然语言处理/算法