leetcode-442-数组中重复的数据


本题是leetcode,地址:442. 数组中重复的数据

题目

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

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

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

示例:

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

输出:
[2,3]

分析

这道题设计的很巧(keng)妙(die),能解决这道题的前提是看懂题目预设数据特点:整数、取值范围:1 ≤ a[i] ≤ n;

基于这两点,设计思路是:

  1. 找到数字i时,将位置i-1处的数字翻转为负数。
  2. 如果位置i-1 上的数字已经为负,则i是出现两次的数字。

这样代码也就出来了;

code

    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> rs = new ArrayList<>();
        for(int index = 0; index < nums.length; index ++) {
            int v = Math.abs(nums[index]);
            int v2 = nums[v -1];
            if(v2 < 0) {
                rs.add(v);
            } else {
                nums[v -1] = -nums[v -1];
            }
        }
        return rs;
    } 

你的鼓励也是我创作的动力

打赏地址

posted @ 2020-07-25 01:22  Yangsc_o  阅读(155)  评论(0编辑  收藏  举报