【剑指offer】_15数组中重复的数字
生活随笔
收集整理的這篇文章主要介紹了
【剑指offer】_15数组中重复的数字
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
在一個長度為n的數組里的所有數字都在0到n-1的范圍內。 數組中某些數字是重復的,但不知道有幾個數字是重復的。也不知道每個數字重復幾次。請找出數組中任意一個重復的數字。 例如,如果輸入長度為7的數組{2,3,1,0,2,5,3},那么對應的輸出是第一個重復的數字2。
解題思路
掃描數組{2,3,1,0,2,5,3}下標為0開始,如果當前位置的數不等于它的下標則與下表為當前元素的值進行交換
代碼實現
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 falsebool duplicate(int numbers[], int length, int* duplication) {if(numbers == nullptr || length <= 0)return false;for(int i=0;i<length;++i){if(numbers[i]<0 || numbers[i]>length-1)return false;}for(int i=0;i<length;++i){while(numbers[i] != i){if(numbers[i] == numbers[numbers[i]]){*duplication = numbers[i];return true;}swap(numbers[i],numbers[numbers[i]]);}}return false;} };總結
以上是生活随笔為你收集整理的【剑指offer】_15数组中重复的数字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 黎明觉醒激活信号塔有什么用
- 下一篇: 【剑指offer】_16 构建乘积数组