day5_array

数组专题

一、同类型题1

1.442 找到所有数组中消失的数字(easy)
class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        int n = nums.length;
        for (int num : nums){
            int x = (num - 1) % n;
            nums[x] += n;
        }
        List<Integer> result = new ArrayList<Integer>();
        for (int i = 0; i<n; i++){
            if (nums[i] <= n){
                result.add(i + 1);
            }
        }
        return result;
    }
}
2.数组中重复的数据(med)

1.空间复杂度O(n)版本

class Solution {
public List<Integer> findDuplicates(int[] nums) {
// 因为只出现1次或2次,不是0,就是1,表示已经出现过1次,直接将当前值(出现了第二次)添加到res中即可
        int n = nums.length;
        List<Integer> res = new LinkedList<>();
        // 用数组模拟哈希集合
        int[] seen = new int[n + 1];
        for (int num : nums) {
            if (seen[num] == 0) {
                // 添加到哈希集合
                seen[num] = 1;
            } else {
                // 找到重复元素
                res.add(num);
            }
        }
        return res;
    }
}

2.空间复杂度常数版本

class Solution2 {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new LinkedList<>();
        for (int num : nums) {
            // 注意索引,nums 中元素大小从 1 开始,
            // 而索引是从 0 开始的,所以有一位索引偏移
            if (nums[Math.abs(num) - 1] < 0) {
                // 之前已经把对应索引的元素变成负数了,
                // 这说明 num 重复出现了两次
                res.add(Math.abs(num));
            } else {
                // 把索引 num - 1 置为负数
                nums[Math.abs(num) - 1] *= -1;
            }
        }

        return res;
    }
}
3.缺失的第一个正数(hard)

重要条件

  1. 理解要找的数一定在[1,N+1]的整数当中,N为传入数组的长度
  2. 将nums[i] 和 nums[nums[i] - 1] 的值进行交换,将当前值 与 索引等于当前值 - 1 对应位置的值交换,比如nums[3] = 1,那么将 nums[3] 和 nums[0]的值进行交换
  3. 对更新后的数组进行遍历,第一个 (nums[i] != i + 1) 的值就是缺失的值,返回 i + 1;若遍历到最后都符合,返回 len + 1
class Solution {
public int firstMissingPositive(int[] nums) {
        int len = nums.length;

        for (int i = 0; i < len; i++) {
            while (nums[i] > 0 && nums[i] <= len && nums[nums[i] - 1] != nums[i]) {
                // 满足在指定范围内、并且没有放在正确的位置上,才交换
                // 例如:数值 3 应该放在索引 2 的位置上
                swap(nums, nums[i] - 1, i);
            }
        }

        // [1, -1, 3, 4]
        for (int i = 0; i < len; i++) {
            if (nums[i] != i + 1) {
                return i + 1;
            }
        }
        // 都正确则返回数组长度 + 1
        return len + 1;
    }

    private void swap(int[] nums, int index1, int index2) {
        int temp = nums[index1];
        nums[index1] = nums[index2];
        nums[index2] = temp;
    }
}
  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值