leetcode: 645. Wrong collection + special return method (only pass all input examples, but exceed time)

leetcode: 645. Wrong collection + special return method

topic:

The set s contains integers from 1 to n. Unfortunately, due to data errors, a certain number in the set was copied to the value of another number in the set, resulting in a loss of a number and a duplicate number in the set.

Given an array nums, it represents the result of an error in the collection S.

Please find out the repeated integers , find the missing integers , and return them in the form of an array .

Example 1:

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

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

Don’t write the analysis process, just upload the code directly, and solve it with violence

class Solution {
    
    
public:
    vector<int> findErrorNums(vector<int>& nums) {
    
    
        int n = nums.size();
        int dig = 0, miss = 0;//dig重复出现的数字,miss丢失的数字

        for(int i = 0;i <= n;i++){
    
      //遍历从1-n的所有数
            int count = 0;//记录使用
            for(int j = 0; j < n; j++){
    
     //遍历nums数组
                if(nums[j] == i)
                    count++;//如果数组中的数字在1-n中出现过,则count一直为1
            }
            if(count ==2)
                dig = i;//重复数字会有俩次加加运算
            else if (count == 0)
                miss = i;//未出现的数字不会出现,则没有加加运算
        }

        return {
    
    dig,miss};
    }
};

return {dig,miss} --> directly return the dig and miss numbers

Since the loop is always looking for miss and dig, and continues to execute the loop when it finds miss and dig, it takes too much time, so when we find miss and dig, we will end the loop.

code show as below:

class Solution {
    
    
public:
    vector<int> findErrorNums(vector<int>& nums) {
    
    
        int n = nums.size();
        int dig = 0, miss = 0;//dig重复出现的数字,miss丢失的数字

        for(int i = 0;i <= n;i++){
    
      //遍历从1-n的所有数
            int count = 0;//记录使用
            for(int j = 0; j < n; j++){
    
     //遍历nums数组
                if(nums[j] == i)
                    count++;//如果数组中的数字在1-n中出现过,则count一直为1
            }
            if(count ==2)
                dig = i;//重复数字会有俩次加加运算
            else if (count == 0)
                miss = i;//未出现的数字不会出现,则没有加加运算
            if (dig > 0 && miss > 0 )
                break;
        }

        return {
    
    dig,miss};
    }
};

Guess you like

Origin blog.csdn.net/weixin_42198265/article/details/114633335