[LeetCode] 20.Search Insert Position

2021. 3. 2. 11:10

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

 

Search Insert Position - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

1. Problem

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.

 

Example 1:

Input: nums = [1,3,5,6], target = 5 Output: 2

 

Example 2:

Input: nums = [1,3,5,6], target = 2 Output: 1

 

Example 3:

Input: nums = [1,3,5,6], target = 7 Output: 4

 

Example 4:

Input: nums = [1,3,5,6], target = 0 Output: 0

 

Example 5:

Input: nums = [1], target = 0 Output: 0

 

2. Code

package leetCode;

public class searchInsertPosition {

	public static void main(String[] args) {
		int[] nums = {1, 3, 5, 7};
		int target = 5;
		
		System.out.println(searchInsert(nums, target));
	}
	public static int searchInsert(int[] nums, int target) {
        for(int i = 0; i < nums.length; i++) {
        	if(nums[i] == target) {
        		return i;
        	} else if(i !=0 && nums[i] > target){
        		return i;
        	} else if(i == 0 && nums[i] > target) {
        		return 0;
        	}
        }
        return nums.length;
    }

}

 

3. Report

이진탐색으로 풀 수 있는 문제다

다음엔 이진 탐색으로 풀어보겠다!!

BELATED ARTICLES

more