[LeetCode] 20.Search Insert Position
2021. 3. 2. 11:10
leetcode.com/problems/search-insert-position/
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
이진탐색으로 풀 수 있는 문제다
다음엔 이진 탐색으로 풀어보겠다!!
'Algorithm > 문제' 카테고리의 다른 글
[LeetCode] 22.Shuffle String (0) | 2021.05.25 |
---|---|
[Study] 21. 두개의 원 반경 안에 있는 좌표 값 찾기 (0) | 2021.03.02 |
[Study] 19.최대 실행 횟수 구하기 (0) | 2021.01.26 |
[LeetCode] 18.Same Tree (0) | 2021.01.22 |
[LeetCode] 17.Add Binary (0) | 2021.01.21 |