Post

leetcode(리트코드)3월03일 challenge268-Missing Number

leetcode March 03일 - Missing Number 문제입니다.

1. 문제

https://leetcode.com/problems/missing-number/


2. Input , Output

Constraints:

  • n == nums.length
  • 1 <= n <= 104
  • 0 <= nums[i] <= n
  • All the numbers of nums are unique.

3. 분류 및 난이도

eazy 난이도입니다.
3월 03일자 챌린지 문제입니다.


4. 문제 해석

  • 0 ~ n의 만큼의 배열이 들어와야합니다. 한 숫자가 누락되었는데 그 숫자를 찾아야합니다.

5. code

c++

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
    int missingNumber(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        for(int i =0;i<nums.size();++i)
            if(nums[i] != i)
                return i;
        return nums[nums.size()-1]+1;
    }
};

python

1
2
3
4
5
6
7
8
class Solution:
    def missingNumber(self, nums: List[int]) -> int:
            nums.sort()
            for i in range (0,len(nums)):
                if nums[i] != i :
                    return i
            return nums[len(nums)-1]+1;


6. 결과 및 후기, 개선점

24ms 100% 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int sum = 0;
        for(auto num : nums)
        {
            sum += num;
        }
        
        int numsLength = nums.size();
        int total = numsLength*(numsLength+1)/2;
        
        return total-sum;
    }
};

정렬이 없이 벡터의 모든 합을 더하고, 정상합에서 빼서 수를 찾습니다.

This post is licensed under CC BY 4.0 by the author.