반응형
728x90
반응형
문제
https://leetcode.com/problems/search-insert-position/
풀이코드
package SITE03_leetcode.easy;
/**
* https://leetcode.com/problems/search-insert-position/
*/
public class E003_leetCode35_SearchInsertPosition {
public static void main(String[] args) {
E003_leetCode35_SearchInsertPosition solution = new E003_leetCode35_SearchInsertPosition();
int[] a = new int[]{1,3,5,6};
System.out.println(solution.searchInsert(a, 7));
}
public int searchInsert(int[] nums, int target) {
int result = 0;
/* 경우의수. 마지막 원소보다 target 이 큰 경우 */
if (nums[nums.length - 1] < target) {
return nums.length;
}
int beforeTarget = nums[0];
/* 경우의 수. 첫번째 원소와 target 이 동일한 경우 */
if (beforeTarget == target) {
return 0;
}
for (int i = 0; i < nums.length; i++) {
if (beforeTarget <= target && target <= nums[i]) {
result = i;
break;
} else {
beforeTarget = nums[i];
}
}
return result;
}
}
이진탐색 사용 풀이
https://leetcode.com/problems/search-insert-position/discuss/15406/My-Java-solution
package SITE03_leetcode.easy;
/**
* https://leetcode.com/problems/search-insert-position/
*/
public class E003_leetCode35_SearchInsertPosition {
public static void main(String[] args) {
E003_leetCode35_SearchInsertPosition solution = new E003_leetCode35_SearchInsertPosition();
int[] a = new int[]{1,3,5,6};
System.out.println(solution.searchInsert(a, 7));
}
// binary search
public int searchInsert(int[] A, int target) {
//error check
if(A == null) {
return 0;
}
//special cases
if(target < A[0]) {
return 0;
}
if(target > A[A.length - 1]) {
return A.length;
}
//perform binary search
int left = 0;
int right = A.length - 1;
while(left <= right) {
int mid = (right - left) / 2 + left;
if(A[mid] == target) {
return mid;
}
else if(target < A[mid]) {
right = mid - 1;
}
else { // target > A[mid]
left = mid + 1;
}
}
return left;
}
}
반응형
'Algorithm > Problem Solving' 카테고리의 다른 글
[leetcode] Easy-58번. Search Insert Position 문제풀이 (0) | 2021.12.14 |
---|---|
[이것이 코딩테스트다] 실전문제3. 음료수 얼려 먹기 (JAVA) (0) | 2021.12.04 |
[leetcode] Medium-49번. Group Anagrams 문제풀이 (0) | 2021.11.25 |
[leetcode] Easy-34번. Find First and Last Position of Element in Sorted Array 문제풀이 (0) | 2021.11.23 |
[leetcode] Easy-31번. Next Permutation 문제풀이 (0) | 2021.11.20 |