《剑指offer》数组中重复的数字
生活随笔
收集整理的這篇文章主要介紹了
《剑指offer》数组中重复的数字
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目:在一個(gè)長(zhǎng)度為n的數(shù)組里的所有數(shù)字都在0到n-1的范圍內(nèi)。 數(shù)組中某些數(shù)字是重復(fù)的,但不知道有幾個(gè)數(shù)字是重復(fù)的。也不知道每個(gè)數(shù)字重復(fù)幾次。請(qǐng)找出數(shù)組中任意一個(gè)重復(fù)的數(shù)字。 例如,如果輸入長(zhǎng)度為7的數(shù)組{2,3,1,0,2,5,3},那么對(duì)應(yīng)的輸出是第一個(gè)重復(fù)的數(shù)字2。
解析:利用選擇排序的思想,當(dāng)循環(huán)到到第i個(gè)元素的時(shí)候,從第i+1個(gè)元素開始找,找到第一個(gè)和第i個(gè)位置的元素相同的話就返回true。
public class Solution {// 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++// 這里要特別注意~返回任意重復(fù)的一個(gè),賦值duplication[0]// Return value: true if the input is valid, and there are some duplications in the array number otherwise false public boolean duplicate(int numbers[],int length,int [] duplication) {boolean flag=false;for(int i=0;i<length;i++){for(int j=i+1;j<length;j++){if(numbers[j]==numbers[i]){duplication[0]=numbers[i];flag=true;return flag;}}}return flag;} }總結(jié)
以上是生活随笔為你收集整理的《剑指offer》数组中重复的数字的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《剑指offer》把字符串转为整数
- 下一篇: 《剑指offer》构建乘积数组