LeetCode-数组中重复的数据

544 阅读1分钟

算法记录

LeetCode 题目:

  给你一个长度为 n 的整数数组 nums ,其中 nums 的所有整数都在范围 [1, n] 内,且每个整数出现 一次 或 两次 。请你找出所有出现 两次 的整数,并以数组形式返回。


说明

一、题目

  你必须设计并实现一个时间复杂度为 O(n) 且仅使用常量额外空间的算法解决此问题。

二、分析

  • 数组中的元素要么重复两次,要么重复一次,排序后重复元素会挨在一起。
  • 只需要遍历一遍数组,相邻存在相同元素则记录。
class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        Arrays.sort(nums);
        List<Integer> ret = new ArrayList();
        for(int i = 1; i < nums.length; i++) {
            if(nums[i] == nums[i - 1]) {
                ret.add(nums[i]);
                i++;
            }
        }
        return ret;
    }
}

总结

换位思考。