코딩테스트/Leetcode

LeetCode [Java] :: 35. Search Insert Position

블로그 주인장 2023. 8. 29.

🎁 문제 링크

https://leetcode.com/problems/search-insert-position/

 

Search Insert Position - LeetCode

Can you solve this real interview question? Search Insert Position - Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must w

leetcode.com

🎁 문제 설명

  • Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity.
  • 서로 다른 정수와 대상 값으로 정렬된 배열이 주어지면, 대상이 발견되면 인덱스를 반환합니다. 그렇지 않으면, 순서대로 삽입된 인덱스를 반환합니다. O(log n) 런타임 복잡도를 가진 알고리즘을 작성해야 합니다.

🎁 입출력 예시

🎁 코드

class Solution {
    public int searchInsert(int[] nums, int target) {
        LinkedList<Integer> list = new LinkedList<>();

        for(int i : nums){
            list.add(i);
        }

        int count = 0;
        while(!list.isEmpty()){
            int p = list.poll();

            if(p >= target){
                break;
            }    
            count++;
        }

        return count;
    }
}

🎁 코드 풀이

1) nums 배열에 있는 값보다 target 값이 큰 지점의 nums 배열에 인덱스 반환

2) 선입선출의 개념으로 하나씩 뺀 값을 비교하여 해당 값이 target보다 크거나 같으면 리턴 진행

반응형

댓글