赞
踩
- package leetcodeday1;
-
- import java.util.HashSet;
- import java.util.Set;
-
- public class SelectArrayRepeat {
- //找到数组中重复的数字
- //在一个长度为n的数组num中所有数字都在0 n-1的范围内,数组内某些数字是重复的,但不知道哪些重复了
- //请找出数组中任意一个重复的数字
- public int findRepeatNumber(int [] nums){
- //使用原地交换法
- int i=0;
- while (i<nums.length){
- if (nums[i]==i){
- i++;
- continue;
- }
- if (nums[nums[i]]==nums[i]){
- return nums[i];
- }
- int tmp=nums[i];
- nums[i]=nums[tmp];
- nums[tmp]=tmp;
- }
- return -1;
- }
- public int findRepeatNumber2(int [] nums){
- //使用集合法
- Set<Integer> set = new HashSet<>();
- for (int num : nums) {
- if (set.contains(num)){
- return num;
- }
- set.add(num);
-
- }
- return -1;
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。