find duplicate

2017-02-09  本文已影响11人  ibyr
Question

Given an array of integers, 1 <= a[i] <= n (n = size of array). Some elements appear twice and others appear once.
Find all the elements that appear twice.

Note
Extension
Solution
public List<Integer> findDuplicate(int[] nums) {
    List<Integer> res = new ArrayList<>();
    if  (nums.length < 1) {
        return res;
    }
    for (int i = 0; i < nums.length; i++) {
        int index = Math.abs(nums[i]) - 1;    // 获取index
        if (nums[index] < 0) {    // 已经被标记过一次
            res.add(index + 1);
        } else {    // 首次遇到,取反,标记一次。
            nums[index] = -nums[index];
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读