leetcode 442 数组中的重复的数字 leetcode 287寻找重复数

给定一个整数数组 a,其中1 ≤ a[i] ≤ n (n为数组长度), 其中有些元素出现两次而其他元素出现一次。

找到所有出现两次的元素。

你可以不用到任何额外空间并在O(n)时间复杂度内解决这个问题吗?

示例:

输入:
[4,3,2,7,8,2,3,1]

输出:
[2,3]

思路:  其实很简单,万物皆可排序,但是讲思路嘛,所以每次给nums[i]-1位置设-1,当遇到-1 直接加入..

class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> list = new ArrayList<>();
        if (nums == null || nums.length == 0)
            return list;
        for (int i = 0;i < nums.length;i++) {
            int location = Math.abs(nums[i]);
            if (nums[location-1] < 0) 
                list.add(location);
            else 
                nums[location-1] = -nums[location-1];
        }   
        return list;
    }
}

leetcode 287  快慢指针明天写

扫描二维码关注公众号,回复: 8921421 查看本文章
发布了315 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_39137699/article/details/103828222