剑指 offer第三题,寻找重复数字

    xiaoxiao2022-07-13  158

    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++ // 这里要特别注意~返回任意重复的一个,赋值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) { if (numbers==null || length<0){ return false; } for(int i=0;i<length;i++){ if(numbers[i]<0||numbers[i]>length-1){ return false; } while(numbers[i]!= i){ if(numbers[i]==numbers[numbers[i]]){ duplication[0]=numbers[i]; } swap(numbers,i,numbers[i]); } } return false; } private void swap(int[]nums,int i,int j){ int temp=nums[i]; nums[i]=nums[j]; nums[j]=temp; } }``` 有以下几个错误,写python写惯了忘记写分号; 忘记定义java数组的形式,int numbers[],和int[] numbers, 自己写函数,忘记在参数里定义属性; 交换的是i和nums[i],在while循环里,num[i]!=i就可以交换下去,直到遇到num[i]=num[num[i]],因为之前num[num[i]]已经放上相应数字里。 注意以下事项,判断不为空,数字不大于n。
    最新回复(0)