내 맘대로 알고리즘/LeetCode 2020 May

May LeetCoding Challenge[Day1] - First Bad Version

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
Given n = 5, and version = 4 is the first bad version.
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true

Then 4 is the first bad version. 

1. 알고리즘을 해결하기 위해서 생각한 방법

 

 - n이라는 input값이 주어진다.

 - 이 때, 해당 Solution이라는 클래스는 VersionControl이라는 클래스를 상속받는다.

 - isBadVersion()이라는 메소드를 제공받는데, 해당 메소드는 version이 들어올 때, BadVersion인 지 확인해준다.

 - 이 떄, 처음으로 BadVersion이 나온다면, 버젼이 무엇인지 찾는 것인데, 가장 간단하게 생각할 수 있는 것은

 O(N)의 속도로 for문을 1부터 n까지 돌리는 것이다.

 - 하지만, 해당 문제에서는 O(N)으로 풀 경우, 시간초과가 발생할 정도의 테스트 케이스가 있기 때문에 다른 방법을 생각해야한다.

 - BinarySearch를 사용하자.

 - 하지만, 해당 문제에서는 int 자료형을 사용하기 때문에 pivot을 구할 때, 조심해주자.

 

2. 알고리즘 작성 중, 어려운 점

 

 - 내 머릿 속에 이진탐색은 없는걸?

 - pivot이 Integer형에 벗어나면 어떻게 할래?

 

3. 내가 작성한 알고리즘

 

/* The isBadVersion API is defined in the parent class VersionControl.
      boolean isBadVersion(int version); */

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int left = 1;
        int right = n;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (isBadVersion(mid)) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }    
    
}

4. 내가 작성한 알고리즘 결과

쥰내 느리네.. 퍼센트에 나오지도 않네

 

 

문제 : https://leetcode.com/explore/featured/card/may-leetcoding-challenge/534/week-1-may-1st-may-7th/3316/

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com