剑指Offer-数组中重复的数字
生活随笔
收集整理的這篇文章主要介紹了
剑指Offer-数组中重复的数字
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目描述
在一個長度為n的數(shù)組里的所有數(shù)字都在0到n-1的范圍內(nèi)。 數(shù)組中某些數(shù)字是重復的,但不知道有幾個數(shù)字是重復的。也不知道每個數(shù)字重復幾次。請找出數(shù)組中任意一個重復的數(shù)字。 例如,如果輸入長度為7的數(shù)組{2,3,1,0,2,5,3},那么對應的輸出是第一個重復的數(shù)字2。
思路
數(shù)組中的數(shù)字都在0到n-1的數(shù)字范圍內(nèi)。如果數(shù)組中沒有重復出現(xiàn)的數(shù)字,那么當數(shù)組排序后數(shù)字i就出現(xiàn)在數(shù)組中下標為i的元素處。那么數(shù)組中如果存在重復數(shù)字的話,有些位置的對應的數(shù)字就沒有出現(xiàn),而有些位置可能存在多個數(shù)字。數(shù)組用numbers表示
那么我們重排這個數(shù)組。從第0個元素開始。
代碼實現(xiàn)
package Array;/*** 數(shù)組中重復的數(shù)字*在一個長度為n的數(shù)組里的所有數(shù)字都在0到n-1的范圍內(nèi)。* 數(shù)組中某些數(shù)字是重復的,但不知道有幾個數(shù)字是重復的。也不知道每個數(shù)字重復幾次。請找出數(shù)組中任意一個重復的數(shù)字。* 例如,如果輸入長度為7的數(shù)組{2,3,1,0,2,5,3},那么對應的輸出是第一個重復的數(shù)字2。* 思路:* 數(shù)組中的數(shù)字都在0到n-1的數(shù)字范圍內(nèi)。如果數(shù)組中沒有重復出現(xiàn)的數(shù)字,那么當數(shù)組排序后數(shù)字i就出現(xiàn)在數(shù)組中下標為i的元素處。那么數(shù)組中如果存在重復數(shù)字的話,有些位置的對應的數(shù)字就沒有出現(xiàn),而有些位置可能存在多個數(shù)字。數(shù)組用numbers表示那么我們重排這個數(shù)組。從第0個元素開始。1、比較numbers[i]和i的值,如果i與numbers[i]相等,也就是對數(shù)組排序后,numbers[i]就應該在對應的數(shù)組的第i個位置處,那么繼續(xù)判斷下一個位置。2、如果i和numbers[i]的值不相等,那么判斷以numbers[i]為下標的數(shù)組元素是什么。2.1、如果numbers[numbers[i]]等于numbers[i]的話,那么就是說有兩個相同的值了,重復了。找到了重復的數(shù)字2.2、如果numbers[numbers[i]]不等于numbers[i]的話,那么就將numbers[numbers[i]]和numbers[i]互換。繼續(xù)進行1的判斷。3、循環(huán)退出的條件是直至數(shù)組最后一個元素,仍沒有找到重復的數(shù)字,數(shù)組中不存在重復的數(shù)字。*/ public class Solution02 {// Parameters:// numbers: an array of integers// length: the length of array numbers// duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;// Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++// 這里要特別注意~返回任意重復的一個,賦值duplication[0]// Return value: true if the input is valid, and there are some duplications in the array number// otherwise falsepublic static void main(String[] args) {int[] arr ={2,3,1,0,2,5,3};int[] duplication = {-1};duplicate(arr,arr.length,duplication);System.out.println(duplication[0]);}public static boolean duplicate(int numbers[],int length,int [] duplication) {if(length<=0||numbers==null){return false;}//判斷數(shù)組數(shù)據(jù)是否合法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[0] = numbers[i];return true;}else{//交換numbers[i]和numbers[numbers[i]]int temp = numbers[i];numbers[i] = numbers[temp];numbers[temp] = temp;}}}return false;} }轉(zhuǎn)載于:https://www.cnblogs.com/wupeixuan/p/8623363.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結
以上是生活随笔為你收集整理的剑指Offer-数组中重复的数字的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2018平安车主卡办理条件 车主卡申请必
- 下一篇: grep 正则匹配