https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

 

Find First and Last Position of Element in Sorted Array - LeetCode

Can you solve this real interview question? Find First and Last Position of Element in Sorted Array - Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in t

leetcode.com

 

이진탐색 두번 시행

1. 시작지점 찾기

2. 끝나는 지점 찾기

 

class Solution {
    public int[] searchRange(int[] nums, int target) {

        int start = -1;
        int end = -1;

        int left = 0;
        int right = nums.length - 1;
        // start 위치 찾기
        while (left <= right) {

            int mid = (left + right) / 2;

            if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
            if (nums[mid] == target) {
                start = mid;
            }
        }

        //end 위치 찾기

        left = 0;
        right = nums.length - 1;
        while (left <= right) {

            int mid = (left + right) / 2;

            if (nums[mid] <= target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
            if (nums[mid] == target) {
                end = mid;
            }
        }

        return new int[]{start, end};
    }
}

https://leetcode.com/problems/jump-game-ii/description/

 

Jump Game II - LeetCode

Jump Game II - You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0]. Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to

leetcode.com

 

문제

nums[i]의 값만큼 인덱스를 점프해서 마지막 인덱스까지 도달하는 최소한의 점프 값을 구해야 한다.

 

tmp 배열을 하나 만들어서 배열의 인덱스 i 까지 올수 있는 최소한의 점프 수를 저장한다.

배열에 이미 값이 있으면 그 값이 최소값이므로, 이미 있는 값이 0 일때만 tmp[출발한 인덱스]의 값에 +1 해준다.

 

코드

 

package LeetCode;

public class L45 {
    public int jump(int[] nums) {
        int[] tmp = new int[nums.length];

		//tmp 배열 만들기
        for (int i = 0; i < nums.length; i++) {
        	// 인덱스값이 배열의 길이를 넘지 않게 해준다.
            for (int j = 1; j < nums[i] + 1 && (i + j) < nums.length; j++) {
            	// 값이 0일때만 새로운 값 지정하기
                if (tmp[i + j] == 0) tmp[i + j] = tmp[i] + 1;
            }
        }

        return tmp[nums.length - 1];
    }
}

https://leetcode.com/problems/find-peak-element/description/

 

Find Peak Element - LeetCode

Find Peak Element - A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. You m

leetcode.com

 

문제

peek 은 양 옆의 수보다 큰 수 

peek을 찾는 문제 

배열의 처음-1 과 마지막+1 자리는 가장 작은 수 되어 있어서 처음이나 마지막 원소가 그 전 원소보다 크면 peek이다

 

you must write an algorithm that runs in O(log n) time.

> 이진 탐색으로 풀어라

 

 

코드 

 

public class L162 {
    public int findPeakElement(int[] nums) {
        int left = 0;
        int right = nums.length - 1;

        while (left < right) {
            int mid = (left + right) / 2;
            if (nums[mid] < nums[mid + 1]) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }

        return left;
    }
}

https://leetcode.com/problems/remove-all-occurrences-of-a-substring/

 

Remove All Occurrences of a Substring - LeetCode

Remove All Occurrences of a Substring - Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed: * Find the leftmost occurrence of the substring part and remove it from s. Return s after re

leetcode.com

 

풀이

StringBuilder 에 indexOf 메서드를 쓰면 part가 포함되어있는 idx를 알려준다. 없으면 -1 리턴.

 -1 이 나올때까지 (포함되어있지 않을때까지) 반복문을 돌리면서 포함되어있으면 delete 해준다.

 

 

public static String removeOccurrences(String s, String part) {
    StringBuilder sb = new StringBuilder(s);

    while (sb.indexOf(part) != -1) {
        sb.delete(sb.indexOf(part), sb.indexOf(part) + part.length());
    }
    return sb.toString();
}

 

https://leetcode.com/problems/compare-version-numbers/description/

 

Compare Version Numbers - LeetCode

Compare Version Numbers - Given two version numbers, version1 and version2, compare them. Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at l

leetcode.com

버전2개를 비교하는 문제 

 

풀이

version 2개를 "." 를 기준으로 split하고

길이를 맞춰서 ArrayList에 넣어줬다. 모자른 부분은 0으로 채워둠.

ArrayList 두개 비교 

 
class Solution {
     public int compareVersion(String version1, String version2) {

        // . 을 기준으로 split
        String[] v1 = version1.split("\\.");
        String[] v2 = version2.split("\\.");
        int maxLength = Math.max(v1.length, v2.length);

        // 0 을 채워 size 동일한 ArrayList 만들기
        List<String> arr1 = getArr(v1, maxLength);
        List<String> arr2 = getArr(v2, maxLength);

        // 크기 비교
        for (int i = 0; i < maxLength; i++) {
            if (Integer.parseInt(arr1.get(i)) > Integer.parseInt(arr2.get(i))) return 1;
            else if (Integer.parseInt(arr1.get(i)) < Integer.parseInt(arr2.get(i))) return -1;
        }

	// 버전이 동일하면 0
        return 0;

    }

    ArrayList<String> getArr(String[] str, int maxLength) {
        ArrayList<String> arr = new ArrayList<>(Arrays.asList(str));

        while (arr.size() != maxLength) {
            arr.add("0");
        }
        return arr;
    }
}

 

+ Recent posts