26ms 5lines C++ clean and concise

  • 0
    Find out how many elments in vector nums and how many distinct values in nums,
    the different above is exactly the appearance time of the duplicate value.
    sum(nums)-sum(set) is the sum of the many times duplicate value.
    size(nums)-size(set) is the appearance time of the duplicate value.
    Then using divide calculation for the answer.
        1. put all the value into set, to make it distinct;
        2. calculate the sum of all the values in nums, variable sum
        3. minus all the values in set from sum
        4. sum/(nums.size()-s.size()) is the duplicate value
    class Solution {
        int findDuplicate(vector<int>& nums) {
            set<int> s(nums.begin(),nums.end());
            int sum = 0;
            for(auto i:nums) sum+=i;
            for(auto i:s) sum-=i;
            return sum/(nums.size()-s.size());

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.