zoukankan      html  css  js  c++  java
  • Leetcode-645 Set Mismatch

    The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.

    Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.

    Example 1:

    Input: nums = [1,2,2,4]
    Output: [2,3]
    

    Note:

    1. The given array size will in the range [2, 10000].
    2. The given array's numbers won't have any order.

    上来很直接的思路就是:开一个数组做hash找重复值,然后利用等差数列求缺失值。时间O(N), 空间O(N)

    // Space complexity O(n)
    // Time complexity O(n)
    class Solution {
    public:
        vector<int> findErrorNums(vector<int>& nums) {
            vector<int> res;
            int n = nums.size();
            int rep, mis;
            int hash[n + 1] = {0};
            for (int i = 0; i < n; i++){
                if (hash[nums[i]] == 0){
                    hash[nums[i]] = 1;
                }
                else{
                    rep = nums[i];
                    break;
                }
            }
            int sum = accumulate(nums.begin(), nums.end(), 0);
            mis = (1 + n) * n / 2 - (sum - rep);
            res.push_back(rep);
            res.push_back(mis);
            return res;
        }
    };

    思路二:  不使用额外的空间的话,就要考虑数组值的特性了。这里的数字全为正。所以我们可以利用数字的正负做一个判断,判断有没有重复出现,以及有没有出现。要是只出现一次,那么对应位置的索引应该是负值,而如果出现两次,那么就不为负值了。

    代码:

    // Space complexity O(1)
    // Time complexity O(n)
    class Solution {
    public:
        vector<int> findErrorNums(vector<int>& nums) {
            vector<int> res;
            int n = nums.size();
            int rep, mis;
            for (int i = 0; i < n; i++){
                if (nums[ abs(nums[i]) - 1] > 0){
                    nums[ abs(nums[i]) - 1] *= -1;
                }
                else{ 
                    res.push_back(abs(nums[i]));
                    
                }
            }
           for (int i = 0; i < n; i++){
               if (nums[i] > 0){
                   res.push_back(i + 1);  // 丢失值对应的索引 - 1 就等于原来数组中没有变化的值(即大于0的值)
               }
           }
            
            
            return res;
        }
    };
  • 相关阅读:
    [转]为什么阿里巴巴要禁用Executors创建线程池?
    支付宝的架构到底有多牛逼!
    [转] Java Agent使用详解
    Spring Boot必备技能之Starter自定义
    面试题:JVM 堆内存溢出后,其他线程是否可继续工作?
    Docker 容器化应用
    Python Click 学习笔记
    MySQL优化(7):其他注意事项
    MySQL优化(6):分表和读写分离
    MySQL优化(5):分区
  • 原文地址:https://www.cnblogs.com/simplepaul/p/7710996.html
Copyright © 2011-2022 走看看