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;
        }
    };
  • 相关阅读:
    Java并发编程的艺术(二)——volatile、原子性
    Java并发编程的艺术(一)——并发编程的注意问题
    算法——朋友圈(并查集)
    算法——汉诺塔问题
    算法——接雨水
    算法——n皇后问题
    深入理解Java虚拟机(八)——类加载机制
    深入理解Java虚拟机(七)——类文件结构
    转-项目管理5阶段|一位高级项目经理的4年项目经验分享
    什么是信息系统项目管理师(高级项目经理)
  • 原文地址:https://www.cnblogs.com/simplepaul/p/7710996.html
Copyright © 2011-2022 走看看