数组中重复的数字
数组中重复的数字
题目链接
题目描述
在一个长度为 n 的数组里的所有数字都在 0 到 n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字是重复的,也不知道每个数字重复几次。请找出数组中任意一个重复的数字。
package com.huang.datastructure;
import com.sun.deploy.util.StringUtils;
/**
* @Author hxc
* @Date 2022/1/4
*/
public class ArraysDemo {
/**
* 在一个长度为 n 的数组里的所有数字都在 0 到 n-1 的范围内。数组中某些数字是重复的,
* 但不知道有几个数字是重复的,也不知道每个数字重复几次。请找出数组中任意一个重复的数字。
*
* ```html
* Input:
* {2, 3, 1, 0, 2, 5}
*
* Output:
* 2
* ```
*/
public static void main(String[] args) {
int[] arr = { 3, 1 , 1, 5 , 0, 2, 5, 5};
//int i = arrayDest(arr);
//System.out.println(i);
int duplicate = duplicate(arr);
System.out.println(duplicate);
}
//第一种解法
public static int arrayDest(int[] arr) {
//时间复杂度为O(MN)
for (int i = 0;i<arr.length;i++) {
int temp = arr[i];
for (int j = 1 + i;j<arr.length;j++) {
if(temp == arr[j]){
return temp;
}
}
}
return -1;
}
//第二种解法
public static int duplicate(int[] nums) {
//时间复杂度为O(N)
for (int i = 0; i < nums.length; i++) {
while (nums[i] != i) {
if (nums[i] == nums[nums[i]]) {
return nums[i];
}
swap(nums, i, nums[i]);
}
swap(nums, i, nums[i]);
}
return -1;
}
private static void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}