[코테 스터디 29일차 TIL] Missing Number

dev_jubby·2024년 8월 19일
1

코테스터디

목록 보기
29/36



💛 오늘의 학습 키워드

[이분탐색(이진탐색)] Missing Number



📝 문제

문제 설명

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

제한 조건

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

입출력 예

Example 1

Input: nums = [3,0,1]
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.

Example 2

Input: nums = [0,1]
Output: 2
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.

Example 2

Input: nums = [0,1]
Output: 2
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.




💬 내 풀이

class Solution {
    public int missingNumber(int[] nums) {
        int n = nums.length;
        int sum = 0;

        for(int i : nums){
            sum += i;
        }

        return (n*(n+1)/2) - sum;
        
    }
}

💻 내 접근 방법

  1. 전체 합에서 배열의 합을 빼면, 누락된 값이 도출되는 사실로 접근을 했다.
  2. 먼저 합계를 구할 sum 변수를 선언하고 for문을 사용해서 nums 배열의 합을 구한다.
  3. 자연수의 합 공식 n*(n+1)/2 를 사용해서 전체 합을 구하고 주어진 nums 배열의 합인 sum 을 빼줌으로써 없는 값을 도출했다.



💦 회고

__




profile
신입 개발자 쥬비의 기술 블로그 입니다.

0개의 댓글