数组中重复的数字

题目描述

在一个长度为 n 的数组里的所有数字都在 0 到 n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字是重
复的,也不知道每个数字重复几次。请找出数组中任意一个重复的数字。

解题思路

对于这种数组元素在 [0, n-1] 范围内的问题,可以将值为 i 的元素调整到第 i 个位置上进行求解。
要求时间复杂度 O(N),空间复杂度 O(1)。因此不能使用排序的方法,也不能使用额外的标记数组。

import java.util.Scanner;
public class Three {
	
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        int[] numbers = stringToArray(str);
		sc.close();
		
		int[] duplication = new int[1];
		int length = numbers.length;
		boolean flag = duplicate(numbers,length,duplication );
		System.out.println(flag);
		System.out.println(duplication[0]);
	}
	
	public static boolean duplicate(int numbers[], int length, int[] duplication) {
		if (numbers == null || length <= 0)
			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;
				}
				swap(numbers, i, numbers[i]);
			}
		}
		return false;
	}

	private static void swap(int[] nums, int i, int j) {
		int temp = nums[i];
		nums[i] = nums[j];
		nums[j] = temp;
	}
	private static int[] stringToArray(String str) {

		String[] temp = str.split(" ");            
		int[] result = new int[temp.length];       
		for (int i = 0; i < temp.length; i++) {
			result[i] = Integer.valueOf(temp[i]);   
		}
		return result;
	}

}
Input:
{2, 3, 1, 0, 2, 5}
Output:
true
2

参考资料

https://github.com/CyC2018/CS-Notes/blob/master/notes/%E5%89%91%E6%8C%87%20Offer%20%E9%A2%98%E8%A7%A3%20-%20%E7%9B%AE%E5%BD%95.md

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值