Find the Duplicate Number
来源:互联网 发布:java 判断对象的大小 编辑:程序博客网 时间:2024/05/16 14:12
https://leetcode.com/problems/find-the-duplicate-number/
题意:固定数组,有一个数字是重复的,找出重复的数字。
解题思路:例如比7小的个数有6个,但实际上却有7个,说明重复数字在是比7小。
class Solution {public: int findDuplicate(vector<int>& nums) { int left = 1,right = nums.size() - 1; int mid; int cnt;//小于或等于mid的个数 while(left < right) { cnt = 0; mid = (left + right) / 2; for(int i = 0;i <= nums.size() - 1;i++){ if(nums[i] <= mid) cnt++; } //如果“小于或等于mid的个数”的个数大于mid,则重复值在左边 if(cnt > mid) right = mid; else left = mid + 1; } return left; }};
哈希解法:将每个数求模,存储到对应的位置上,如果同一个下标已经存储了,则表示数字重复。
class Solution {public: int findDuplicate(vector<int>& nums) { int len = nums.size(); int hash[len]; int r,index; for(int i = 0;i < len;i++) hash[i] = -1; for(int i = 0;i < len;i++){ r = nums[i] % len; if(hash[r] != -1){ index = i; break; } else hash[r] = nums[i]; } return nums[index]; }};
0 0
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find The Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- 数据库索引相关
- Dynamic Web Module 3.1 requires Java 1.7 or newer
- nc65 删除时提示未实现接口nc.uap.pf.metadata.HeadBodyQueryImpl
- 删除windosw 下的 oracle 服务
- android各种资源下载
- Find the Duplicate Number
- 微服务实战(四):服务发现的可行方案以及实践案例
- 云平台域名相关功能对比
- codeforces #334 B. Eight Point Sets
- 交叉熵公式推导
- 微服务实践(五):微服务的事件驱动数据管理
- 2016中国设备管理大会暨第十四届全国TnPM大会在无锡市胜利召开!
- RabbitMQ (一) 入门 Helloworld
- 为毛老抱怨工资低又不离职