剑指offer-数组中重复的数字
来源:互联网 发布:多玩tbc数据库 编辑:程序博客网 时间:2024/06/05 00:30
问题
题目:[剑指offer-数组中重复的数字]
思路
这个题我觉得其实它也没说清楚,看了注释才明白。
要得到所有重复的数字。
那我就判断一下,第一次重复数字出现的时候得到,通过first标记来判断是不是第一次。
代码
class Solution {public: // Parameters: // numbers: an array of integers // length: the length of array numbers // duplication: (Output) the duplicated number in the array number // Return value: true if the input is valid, and there are some duplications in the array number // otherwise false bool duplicate(int numbers[], int length, int* duplication) { sort( numbers, numbers + length ); int sz = length; int k = 0; int first = 1; for(int i = 1; i < sz; ++i){ if( numbers[i-1] == numbers[i] && 1 == first ){ duplication[k++] = numbers[i]; first = 0; } else if( numbers[i-1] != numbers[i]) first = 1; } return k > 0; }};
思路1
参考了下这篇链接:[(剑指Offer)面试题51:数组中重复的数字]
发现自己在做的时候,对题目的理解不正确。
题目的意思是判断数组中是否存在重复的数字,如果有重复的,返回第一个重复的就可以了。
这么考虑,如果没有重复的。那么肯定是a[i] = i;这种情形。如果有,就不是了。
所以,对于任意一个位置i,判断a[i] == i,如果相等,则没事。
如果,不相等,则loc = a[i],也即a[i]应该在loc的位置上。那么判断,a[i] == a[loc],则证明已经有重复元素。返回true。否则,交换。这样可以保证a[loc] == a[i],即loc存储的是本生的元素。对于a[i],继续判断。
class Solution {public: // Parameters: // numbers: an array of integers // length: the length of array numbers // duplication: (Output) the duplicated number in the array number // Return value: true if the input is valid, and there are some duplications in the array number // otherwise false bool duplicate(int numbers[], int length, int* duplication) { if( !numbers || length < 1 || !duplication ) return false; for(int i = 0; i < length; ++i){ while( numbers[i] != i ){ int loc = numbers[i]; if( numbers[i] == numbers[loc] ){ *duplication = numbers[i]; return true; } std::swap( numbers[i], numbers[loc] ); } } return false; }};
阅读全文
0 0
- 剑指offer--数组中重复的数字
- 《剑指offer》数组中重复的数字
- 剑指offer:数组中重复的数字
- [剑指Offer]数组中重复的数字
- 剑指offer:数组中重复的数字
- 剑指offer 数组中重复的数字
- [剑指offer]数组中重复的数字
- 剑指offer|数组中重复的数字
- 剑指offer-数组中重复的数字
- 剑指offer 数组中重复的数字
- 《剑指offer》数组中重复的数字
- 剑指offer-数组中重复的数字
- 剑指offer--数组中重复的数字
- 剑指offer--数组中重复的数字
- 剑指offer:数组中重复的数字
- 剑指offer:数组中重复的数字
- 剑指offer:数组中重复的数字
- 【剑指offer】数组中重复的数字
- 面试干货
- 【转】使用AWS、Docker与Rancher提供弹性的生产级服务
- 查看idea的后台任务
- Linux网络编程-UDP接收数据丢包解决方案
- js中巧用cssText属性批量操作样式
- 剑指offer-数组中重复的数字
- 从局域网中获得服务器中的JSON和XML,进行解析
- 命令行运行jar包(idea+gradle)的两种方式
- 古文觀止卷七_阿房宮賦_杜牧
- ThinkPHP的路由
- hdu 2009 求数列的和
- 摄像机原理与视频运动模糊的解释
- 集群基础-----(iscsi远程共享存储)
- bootstrap分页的要求也适用于基本分页