막무가내로 삽질하는 알고리즘 16

MaximumSubArray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. 기본 합산 값과 대비해서 다른 원소들의 합산 값을 max 로 비교 마지막 수에 대한 고려가 없으므로 마지막 수 비교. private static int solve(int[] nums) { int max = 0; for(int i=0; i

Longest Substring With At Most Two Distinct

포인터다. 정말 생소하디 생소한, 버퍼에서나 사용해봤던 그 포인터. Map을 선언하여 문자와 포인터에 걸린 문자수를 저장한다. if문으로 가져온 값이 1이라면 새로운 문자를 넣은 것이므로 counter 는 증가 길이 추출을 위해 end 포인터를 증가 시킴 새로운 글자 추출로 인해 count 가 허용한 2를 넘어갈시에 start 포인터의 글자만큼 map에서 수를 삭감 한글자가 모두 삭감되었을때 count-- 삭감되는 동안 start 포인터는 기준점을 옮기기 위해 증가함 매번 length 를 max 함수로 구하므로 포인터로 잡은 최대 length는 변수에 언제나 저장되어 있음. public class LongestSubstringWithAtMostTwoDistinctRepeat { public static ..

UniqueEmailAddresses

문자열 조작은 생각만치 언제나 쉽지않다. StringBuilder 를 사용해보려고 노력해도 쉽지가 않더라. Every email consists of a local name and a domain name, separated by the @ sign. For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name. Besides lowercase letters, these emails may contain '.'s or '+'s. If you add periods ('.') between some characters in the local name part of an email address, ..

KClosest

Example 1: Input: points = [[1,3],[-2,2]], K = 1 Output: [[-2,2]] Explanation: The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]]. 우선순위 큐 , 람다를 씀. 각 원소의 제곱의 합의 제곱근을 비교해서 정렬시킴 정렬은 내부 이진트리구조에서 정..

다리를 지나는 트럭

미팅룸과 비슷하다고 봤었음. 새로운 트럭이 있을경우 +1 초 만큼 증가한다고 생각했음 트럭이 큐에 들어올떄 마다 분기해서, 시간을 추가해주고 나중에 추가시간을 병합해주기로 했었음. 테스트 케이스는 맞았으나 제출 후 많이 실패함. 트럭 클래스를 만들고 while 문을 걸어서 시간을 -1 해서 풀어야하나 생각하고 있음. import java.util.*; class Solution { public int solution(int bridge_length, int weight, int[] truck_weights) { Queue queue = new PriorityQueue(truck_weights.length); int answer = 1; int sec = 0; for(int i=0; i 10 안걸림 que..

LicenseKeyFormatting

k 만큼의 글자를 그룹화한 뒤 하이픈을 추가한다. 글자는 모두 대문자여야하고 , k만큼의 글자로 그룹화 되지 않는 부분은 첫 그룹에 묶는다. 길이 체크 후 대문자로 바꿈. StringBuffer 로 하이픈을 찾아 없앰 k보다 작아 그룹화할 수 없다면 그대로 리턴 k보다 크다면 역순으로 탐색하며 count가 k 의 배수일 때 하이픈 추가 public class LicenseKeyFormatting { public static void main(String[] args) { String str1 = "8F3Z-2e-9-w"; String str2 = "8-5g-3-J"; int k = 4; String answer = solve(str2, k); System.out.println(answer); } /** ..

JewelsAndStones

List 사용, subStr 로 잘라 비교해서 count 증가 리턴 public class JewelsAndStones { public static void main(String[] args) { String J = "aA"; String S = "aAAbbbb"; int answer = solve(J,S); System.out.println(answer); } /** * 각 문자는 돌의 종류를 나타낸다. 각 돌에서 보석이 몇개 있는지 알려달라. * @param j * @param s * @return */ private static int solve(String j, String s) { //List 를 이용해서 문자열을 잘라 놓고 비교한다. if(s.length() == 0) { return 0; }..

MeetingRoom2

회의의 시작과 끝이 주어짐 총 회의에서 사용될 회의실 수를 리턴해라. intervals 의 length 가 0 이 아닌이상 1개의 방은 무조건 있음 이후 start, end를 비교해서 겹치면 방 추가함 public class MeetingRoom2 { public static void main(String[] args) { Interval interval1 = new Interval(0, 30); Interval interval2 = new Interval(5, 10); Interval interval3 = new Interval(15, 20); Interval interval4 = new Interval(7,10); Interval interval5 = new Interval(2, 4); Interva..