ARTS 第四周

Algorithm

442.Find All Duplicates in an Array

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 in this array.

Could you do it without extra space and in O(n) runtime?

Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]

题意:给一个数组,且1<=a[i]<=n (n为数组的元素大小),数组中有一些出现两次的元素,也有出现一次的元素。找出所有出现两次的元素。
思路:我自己是没有任何思路,看到评论的题解如下。这里加粗的条件非常重要,可以确保a[a[i]-1]合法。

题解一

//遍历数组,可以是a[i]对应的a[a[i]-1]位置的数变为-a[a[i]-1],那么如果第二次遇到前面相同的数字时,就有a[i]<0。那么这就可以找出来了。
public class Solution {
    // when find a number i, flip the number at position i-1 to negative. 
    // if the number at position i-1 is already negative, i is the number that occurs twice.
    
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < nums.length; ++i) {
            int index = Math.abs(nums[i])-1;
            if (nums[index] < 0)
                res.add(index+1);
            nums[index] = -nums[index];
        }
        return res;
    }
}

题解二

//遍历nums数组,如果nums[i]和nums[nums[i]-1]不相等,那么交换,如果相等则i++
//这么做的目的是为了把每个数字都放到对应nums[i]-1的位置,那么最终不再nums[i]-1位置的,即为重复的数字。
class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        vector<int> res;
        int i = 0;
        while (i < nums.size()) {
            if (nums[i] != nums[nums[i]-1]) swap(nums[i], nums[nums[i]-1]);
            else i++;
        }
        for (i = 0; i < nums.size(); i++) {
            if (nums[i] != i + 1) res.push_back(nums[i]);
        }
        return res;
    }
};

Review

学习繁忙以后再补。

Tip

Linux(一)网络管理

Share

这篇文章借鉴了皓叔的文章TCP的哪些事儿

计算机网络(一)TCP

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值