前言
10.30打卡,你今天坚持了吗?
题目
leetcode-287 寻找重复数字
分类(tag): 二分查找这一类
英文链接:
https://leetcode.com/problems/find-the-duplicate-number/
中文链接:
https://leetcode-cn.com/problems/find-the-duplicate-number/
题目详述
给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。
示例 1:
输入: [1,3,4,2,2]输出: 2
示例 2:
输入: [3,1,3,4,2]输出: 3
说明:
题目详解
思路
代码
class Solution {
public int findDuplicate(int[] nums) {
int low = 1;
int high = nums.length;
int mid = low + (high - low) / 2;
while(low < high)
{
int count = 0;
mid = low + (high - low) / 2;
for(int i=0;i<nums.length;i++)
{
if(nums[i] <= mid)
count++;//1 2 3 3 4
}
if(count > mid)
high = mid;
else
low = mid + 1;
}
return low;
}
}
结束语
10.30号打卡,有些说需要leetcode视频资源,可以看看我今天刚发的另一篇文章,里面有算法视频资源~
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有