解决问题思路1.
代码实现:
package j2; import java.util.Arrays; /** * Created by admin on 2019/5/8. */ public class FindDuplicate { public static void duplicate(int[] numbers,int length,int[]duplication){ //边界条件的判断 if (numbers == null || length==0) { return ; } Arrays.sort(numbers); int j=0; for (int i=0;i<length-1;i++) { if (numbers[i] == numbers[i+1]) { duplication[j] = numbers[i]; j++; } } } public static void main(String[] args) { int[] arr={2,3,1,0,2,5,3}; int[] duplicate = new int[arr.length]; duplicate(arr,arr.length,duplicate); System.out.println(Arrays.toString(duplicate)); } }
解题思路2.
代码实现:
解题思路3.
代码实现:
package j2; import java.util.Arrays; /** * Created by admin on 2019/5/8. */ public class FindDuplicate2 { /*** * 推荐的做法是:通过交换元素将i保存到numbers[i]中 * 在numbers[i]不和i相等的时候,如果number[i]和numbers[numbers[i]]相等就说明是重复的元素 * 否则就交换这两个元素,这个过程就是相当于排序 * @param numbers * @param length * @param duplication */ public static void duplicate(int[] numbers,int length,int[]duplication){ if (numbers == null || length<= 0) { return ; } for (int i=0;i<length;i++) { if (numbers[i]<0 || numbers[i]>length-1) { return; } } //如果i下标和i所指定的元素不同,那么我们就要进行交换,否则再比较要找的元素是否和i所指定的元素相同,如果是就是重复的元素 int k=0; for (int i=0;i<length;i++) { while (numbers[i] != i){ //现在numbers[i] != i,设numbers[i]=j,所以如果下面的if成立,就是numbers[i] = numbers[j],说明重复 if (numbers[i] == numbers[numbers[i]]) { duplication[k] = numbers[i]; k++; break; } //交换元素 swap(numbers,i,numbers[i]); } } } //交换元素 private static void swap(int[] numbers, int p, int q) { int temp = numbers[p]; numbers[p] = numbers[q]; numbers[q] = temp; } public static void main(String[] args) { int[] arr={2,3,1,0,2,5,3}; int[] duplicate = new int[arr.length]; duplicate(arr,arr.length,duplicate); System.out.println(Arrays.toString(duplicate)); } }