반응형
반응형
문제 풀이 문자열(stones)에 원하는 문자(jewels)가 몇 개가 포함되어 있는 지를 세는 문제이다. 대소문자를 구분하고 인풋은 영어 문자만 들어온다. 코드 jewels 를 Set으로 만들고 각 stone마다 순회하면서 포함되어 있으면 카운트를 늘리는 방식으로 풀었다. class Solution { public int numJewelsInStones(String jewels, String stones) { Set jewel = jewels.chars() .mapToObj(e->(char)e) .collect(Collectors.toSet()); int result = 0; for(Character stone : stones.toCharArray()){ if(jewel.contains(stone)){..
문제 풀이 오름차순으로 정렬된 배열에 원하는 값을 찾는 문제이다. 문제 이름대로 이진 탐색을 이용해서 풀면 되는 문제다. 이진 탐색은 정렬된 리스트에서 값을 탐색하는 알고리즘이다. 아래와 같이 매번 탐색이 진행될 때마다 범위를 1/2씩 좁혀서 가면서 탐색한다. 그래서 시간 복잡도는 O(logN)이다. 배열에 원하는 값이 존재하면 원하는 값의 인덱스를 반환하고 아니면 -1을 반환하면 된다. 그래서 해당 문제의 종료 조건은 아래와 같이 구현할 수 있다. 원하는 값을 찾았을 때 return 원하는 값의 인덱스 왼쪽인덱스가 오른쪽 인덱스보다 큰 경우, 원하는 값이 배열에 없는 경우이다. return -1 코드 class Solution { public int search(int[] nums, int target..
문제 You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the step with index 0, or the step with index 1. Return the minimum cost to reach the top of the floor. Example 1: Input: cost = [10,15,20] Output: 15 Explanation: Cheapest is: start on cost[1], pay that cost, and go ..