剑指offer - 数组中重复的数字
数组中重复的数字
http://www.nowcoder.com/questionTerminal/623a5ac0ea5b4e5f95552655361ae0a8
Method 1 Time:O(n) Space:O(1)
Method 2 Time:O(n) Space:O(n)
Special Test Case: [6,3,2,0,2,5,0]
public class Solution { public boolean duplicate(int numbers[],int length,int [] duplication) { if(numbers == null || length <= 0) { return false; } for(int i = 0; i < length;i++) { int index = numbers[i]; if(index < 0 || index >= length) { return false; } if(index == i) { continue; } if(numbers[index] == index) { duplication[0] = index; return true; }else{ numbers[i] = numbers[index]; numbers[index] = index; // swap once } } return false; } } import java.util.*; public class Solution { public boolean duplicate(int numbers[],int length,int [] duplication) { if(numbers == null || length <= 0) { return false; } LinkedHashSet<Integer> set = new LinkedHashSet<>(); for(int i = 0;i < length;i++) { int val = numbers[i]; if(val < 0 || val >= length) { break; }else if(set.contains(val)) { duplication[0] = val; return true; } set.add(val); } return false; } }