반응형
Recent Posts
Notice
Recent Comments
Link
250x250
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- coding
- two pointers
- 리트코드
- programmers
- ArrayList
- 우선순위 큐
- string
- dfs
- recursion
- binary tree
- leetcode
- PCCP
- Algorithm
- 알고리즘
- Array
- Java
- 깊이우선탐색
- DP
- 부분배열
- 브루트포스
- 재귀함수
- priority queue
- greedy
- HashMap
- hashset
Archives
- Today
- Total
지식창고
[Java] LeetCode 35. Search Insert Position 본문
728x90
반응형
[Java] LeetCode 35. Search Insert Position
문 제 :
정렬된 정수 배열 nums가 주어진다.
그리고 정수 target이 주어진다.
target이 nums에 있다면, 있는 index를, 없다면 들어가야 할 index를 반환해라.
단, 시간복잡도가 O(log n) 이여야한다.
Constraint
{ 1 <= nums.length == 10^4 }
{ -10^4 == nums[i] <= 10^4 }
{ 1 <= n <= 100 }
{ grid[i][j] is 0 or 1 }
Example )
Input: nums = [1,3,5,6], target = 5
Output: 2
//////////////////////////////////////////////////////////
Input: nums = [1,3,5,6], target = 2
Output: 1
//////////////////////////////////////////////////////////
Input: nums = [1,3,5,6], target = 7
Output: 4
접 근 :
배열을 반으로 갈라서 그 지점보다 큰지 작은지를 판단하면서 찾아간다.
해 결 :
첫 시작점 s 는 0부터 시작한다.
첫 끝 점 e는 nums.length-1 부터 시작한다.
s와 e의 중간지점 m을 구한다.
조건에 따라 범위를 좁혀가며 target의 index를 구해준다.
결 과 :
class Solution {
public int searchInsert(int[] nums, int target) {
int s = 0;
int e = nums.length-1;
int m = s + e / 2;
while(s <= e) {
m = s + (e - s) / 2;
if(target > nums[m]) s = m + 1;
else if(target < nums[m]) e = m - 1;
else return m;
}
return s;
}
}
728x90
반응형
'Algorithm > Leetcode' 카테고리의 다른 글
[Java] LeetCode 122. Best Time to Buy and Sell Stock II (0) | 2023.02.21 |
---|---|
[Java] LeetCode 540. Single Element in a Sorted Array (2) | 2023.02.21 |
[Java] LeetCode 1162. As Far from Land as Possible (0) | 2023.02.10 |
[Java] LeetCode 6. Zigzag Conversion (0) | 2023.02.03 |
[Java] LeetCode 953. Verifying an Alien Dictionary (1) | 2023.02.02 |
Comments