645. Set Mismatch(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83507418

题目:

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:
The given arraysize will in the range [2, 10000]. The given array’s numbers won’thave any order.

解释:
集合中本来包含从1n的数字,可惜其中一个数字变成了另一个数字,请找到出现了两次的数字和这个发生了变化的数字。
set()就可以很好地解决问题。
对于连续的数组求和可以用n*(n+1)/2简化问题。
python代码:

class Solution(object):
    def findErrorNums(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        n=len(nums)
        set_nums=set(nums)
        sum_set_nums=sum(set_nums)
        return [sum(nums)-sum_set_nums,n*(n+1)/2-sum_set_nums]

c++代码:

class Solution {
public:
    vector<int> findErrorNums(vector<int>& nums) {
        int n=nums.size();
        set<int>_set(nums.begin(),nums.end());
        vector<int>result ;
        int sum_set=accumulate(_set.begin(),_set.end(),0);
        int sum_nums=accumulate(nums.begin(),nums.end(),0);
        result.push_back(sum_nums-sum_set);
        result.push_back(n*(n+1)/2-sum_set);
        return result;
    }
};

总结:
合理使用set(),用n*(n+1)/2减少求和时间。

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/83507418