码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 442. 数组中重复的数据 java

时间:2019-05-20 22:40:43      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:==   int   public   etc   输出   solution   给定一个整数数组   new   res   

题目:

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

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

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

示例:

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

输出:
[2,3]

解题:

class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new ArrayList<>();
        if (nums == null || nums.length == 0) return res;
        for (int i = 0; i < nums.length; i++) {
            int index = Math.abs(nums[i]) - 1;
            if (nums[index] > 0) nums[index] *= -1; //用负号表示已经有一次了
            else {
                res.add(index + 1); //index + 1 == Math.abs(nums[i])
            }
        }
        return res;
    }
}

 

leetcode 442. 数组中重复的数据 java

标签:==   int   public   etc   输出   solution   给定一个整数数组   new   res   

原文地址:https://www.cnblogs.com/yanhowever/p/10896984.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!