Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- d
- 티스토리 쿠키 삭제
- 처음 만나는 AI수학 with Python
- 자바편
- /etc/network/interfaces
- 자료구조와 함께 배우는 알고리즘 입문
- 코드로배우는스프링웹프로젝트
- iterator
- 선형대수
- 스프링 시큐리티
- 네트워크 설정
- Kernighan의 C언어 프로그래밍
- 친절한SQL튜닝
- baeldung
- 알파회계
- 처음 만나는 AI 수학 with Python
- 이터레이터
- 데비안
- 리눅스
- resttemplate
- 스프링부트핵심가이드
- GIT
- 목록처리
- ㅒ
- network configuration
- 자료구조와함께배우는알고리즘입문
- 구멍가게코딩단
- 서버설정
- 페이징
- 코드로배우는스프링부트웹프로젝트
Archives
- Today
- Total
bright jazz music
Binary Search (이진검색) 본문
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
Constraints:
- 1 <= nums.length <= 104
- -104 < nums[i], target < 104
- All the integers in nums are unique.
- nums is sorted in ascending order.
---
class Solution {
public int search(int[] nums, int target) {
int pivot, left = 0, right = nums.length - 1;
while (left <= right) {
pivot = left + (right - left) / 2;
if (nums[pivot] == target) return pivot;
if (target < nums[pivot]) right = pivot - 1;
else left = pivot + 1;
}
return -1;
}
}
---
처음 접해본 알고리즘 문제. 처음이라 그런지 어떻게 풀어야 할지 감도 오지 않았다. 기본적인 개념은 전체 배열을 절반으로 쪼개가면서 조회해야 할 선택지(배열의 구성요소)를 줄여나간다는 데 있다. 배열을 쪼갤 때는 쪼갤 기준이 존재해야 한다. 여기서는 변수 pivot을 중심값이 되는 기준으로 한다.
처음에는 배열의 전체 길이에서 배열의 첫째 값을 뺀다.
'Algorithm&Data structure' 카테고리의 다른 글
배열을 역순으로 정렬하기 (0) | 2022.05.02 |
---|---|
신고 결과 받기 (0) | 2022.04.19 |
숫자 문자열과 영단어 (0) | 2022.04.13 |
Comments