1. 程式人生 > >645. Set Mismatch(python+cpp)

645. Set Mismatch(python+cpp)

題目:

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減少求和時間。