전체 글 (261)
2022-01-17 00:44:12
반응형

다리를 지나는 트럭

 

 문제 설명

 

트럭 여러 대가 강을 가로지르는 일차선 다리를 정해진 순으로 건너려 합니다.

모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 알아내야 합니다.

다리에는 트럭이 최대 bridge_length대 올라갈 수 있으며, 다리는 weight 이하까지의 무게를 견딜 수 있습니다.

단, 다리에 완전히 오르지 않은 트럭의 무게는 무시합니다.

예를 들어, 트럭 2대가 올라갈 수 있고 무게를 10kg까지 견디는 다리가 있습니다.

무게가 [7, 4, 5, 6]kg인 트럭이 순서대로 최단 시간 안에 다리를 건너려면 다음과 같이 건너야 합니다.

경과 시간 다리를 지난 트럭 다리를 건너는 트럭 대기 트럭
0 [] [] [7,4,5,6]
1~2 [] [7] [4,5,6]
3 [7] [4] [5,6]
4 [7] [4,5] [6]
5 [7,4] [5] [6]
6~7 [7,4,5] [6] []
8 [7,4,5,6] [] []

 

따라서, 모든 트럭이 다리를 지나려면 최소 8초가 걸립니다.

solution 함수의 매개변수로 다리에 올라갈 수 있는 트럭 수 bridge_length, 다리가 견딜 수 있는 무게 weight, 트럭 별 무게 truck_weights가 주어집니다.

이때 모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 return 하도록 solution 함수를 완성하세요.

 

 제한 사항

 

  • bridge_length는 1 이상 10,000 이하입니다.
  • weight는 1 이상 10,000 이하입니다.
  • truck_weights의 길이는 1 이상 10,000 이하입니다.
  • 모든 트럭의 무게는 1 이상 weight 이하입니다.

 

 입출력 예

 

bridge_length weight truck_weights return
2 10 [7,4,5,6] 8
100 100 [10] 101
100 100 [10,10,10,10,10,10,10,10,10,10] 110

 

 Python 코드

 

# 시간 초과 코드

def solution(bridge_length, weight, truck_weights):
    answer = 0
    bridge = [0] * bridge_length # 다리 위의 리스트를 선언
    
    while len(bridge):
        answer += 1   # 1초씩 증가
        bridge.pop(0) # 다리 왼쪽 끝의 트럭을 pop
        if truck_weights: # 대기하는 트럭이 있다면
            bridge.append(truck_weights.pop(0)) # 다리에 트럭 추가
        else:
            bridge.append(0) # 무게가 아니라면 다리에 아무도 가지 않는다.
    return answer

* 참고 링크 1 : https://par3k.tistory.com/224

from collections import deque

def solution(bridge_length, weight, truck_weights):
    truck_weights = deque(truck_weights)   # truck_weights(대기트럭)을 담을 deque 생성
    bridge = deque([0 for _ in range(bridge_length)]) # 다리 길이만큼 0을 채워서 변수 생성 // 다리를 건너는 트럭
    time = 0           # 경과 시간
    bridge_weight = 0  # 지금 다리 위의 무게 // 현재 다리를 건너고 있는 무게

    while len(bridge) != 0:
        out = bridge.popleft() # 다리를 건너는 첫번째 트럭(bridge[0])를 pop 해줌
        bridge_weight -= out # 다리 무게에서 다리를 건넌 트럭의 무게를 빼줌
        time += 1 # 시간을 더해줌
        if truck_weights:  # deque에 요소가 남아 있으면 True
            # 현재 다리를 건너는 트럭의 무게와 다리에 오를 트럭의 무게의 합이
            if bridge_weight + truck_weights[0] <= weight:
                # 다리가 견딜 수 있는 무게 이하일 때
                left = truck_weights.popleft() # 대기트럭 deque에서 다음 트럭을 pop하고
                bridge_weight += left # 다리를 건너고 있는 트럭 무게에 더하고
                bridge.append(left) # 건너는 트럭 리스트에 넣어준다.
            else:
                # 다리가 견딜 수 있는 무게 초과일 때
                bridge.append(0) # 다음 트럭이 지나가지 못하므로 0을 채워준다.
    return time

* 참고 링크 2 : https://coblin.xyz/29

 

* 그림 설명 참고 링크 : https://eunhee-programming.tistory.com/149

* 참고 링크 3 : https://latte-is-horse.tistory.com/130

* 유튜브 설명 링크 : https://www.youtube.com/watch?v=Y9HYe4cUiZM&t=388s 

* deque 

  • 양쪽 끝에서 빠르게 추가와 삭제를 할 수 있는 리스트류 컨테이너
  • 양방향 큐
  • 데이터의 회전도 가능
  • maxlen을 설정하여 최대 항목 수를 설정

* 참고 링크 4 : https://www.youtube.com/watch?v=05roQ6gFwsM 

 C++ 코드

 

#include <queue>
#include <vector>

using namespace std;

int solution(int bridge_length, int weight, vector<int> truck_weights) {
    int answer = 0;
    
    int idx=0;    //차량 지목용 idx
    int sum=0;   //현재 다리에 올라와있는 차량 무게 총합
    queue<int> q;  //현재 다리를 건너는 트럭 체크용 큐
    
    while(1){
        
        if(idx == truck_weights.size()){  //마지막 트럭일 때
            answer += bridge_length;  //마지막 트럭이 지나는 시간 추가
            break;  
        }
        
        answer++; //시간초 증가
        int tmp = truck_weights[idx];
        
        //차가 다리를 다 건넜을 경우
        if(q.size() == bridge_length){
            sum -= q.front();  //다 건넜으니 현재 다리에 있는 차들의 무게에서 제외
            q.pop();  
        }
        
        if(sum + tmp <= weight){  //다리에 다음 차가 진입할 수 있다면
            sum += tmp;  //차량 무게 추가
            q.push(tmp);  
            idx++;  //다음 차량을 위해서
        }else{   
            q.push(0);  //진입할 수 없다면 0을 푸시해서 시간초 계산
        }
    }
   
    return answer;
}

 

* 참고 링크 : https://velog.io/@qhsh866/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4Level2-%EB%8B%A4%EB%A6%AC%EB%A5%BC-%EC%A7%80%EB%82%98%EB%8A%94-%ED%8A%B8%EB%9F%AD-C

 

 출처

 

https://programmers.co.kr/learn/courses/30/lessons/42583

반응형
2022-01-14 08:59:30
반응형

43. Multiply Strings

 

 문제 설명

 

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

 

 제한 사항

 

  • 1 <= num1.length, num2.length <= 200
  • num1 and num2 consist of digits only.
  • Both num1 and num2 do not contain any leading zero, except the number 0 itself.

 

 입출력 예

 

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

 

 Python 코드

 

Python code 

class Solution:
    def multiply(self, num1: str, num2: str) -> str:
        def str_to_int(num_str):
            num = 0
            for i, c in enumerate(num_str[::-1]):
                num += pow(10, i) * (ord(c) - ord('0'))
            return num

        return str(str_to_int(num1) * str_to_int(num2))

* 참고 링크 : https://wellsw.tistory.com/94?category=1054641

 

 C++ 코드

 

C ++ code

class Solution {
public:
	string multiply(string num1, string num2) {
		string res(num1.size() + num2.size(), '0');
		for (int i = num1.size() - 1; i >= 0; --i) {
			int carry = 0;
			for (int j = num2.size() - 1; j >= 0; --j) {
				int tmp = (res[i + j + 1] - '0') + (num2[j] - '0')*(num1[i] - '0') + carry;
				res[i + j + 1] = tmp % 10 + '0';
				carry = tmp/10;
			}
			res[i] += carry;
		}
		auto pos = res.find_first_not_of('0');
		if (pos == string::npos)
			return "0";
		return res.substr(pos, res.length() - pos);
	}
};

* 참고 링크 : https://blog.fearcat.in/a?ID=00850-66ef66e8-11ca-463c-82ae-c4af5cb77fae

 

 출처

 

https://leetcode.com/problems/multiply-strings/

반응형
2022-01-14 07:12:08
반응형

Remove Element

 

 문제 설명

 

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

Custom Judge:

The judge will test your solution with the following code:

int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
                            // It is sorted with no values equaling val.

int k = removeElement(nums, val); // Calls your implementation

assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
    assert nums[i] == expectedNums[i];
}

If all assertions pass, then your solution will be accepted.

 제한 사항

 

  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 50
  • 0 <= val <= 100

 

 입출력 예

 

Example 1:

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).

Example 2:

Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).

 

 Python 코드

 

Python code 

class Solution: 
    def removeElement(self, nums: List[int], val: int) -> int:
        answer = [num for num in nums if num != val] 
        for i in range(len(answer)): 
            nums[i] = answer[i] 
            
        nums = nums[:len(answer)] 
        return len(nums)

 

* 참고 링크 : https://somjang.tistory.com/entry/leetCode-27-Remove-Element-Python

https://redquark.org/leetcode/0027-remove-element/

class Solution:
    def removeElement(self, nums, val):
        for i in range(len(nums)):
            if nums[0] != val:
                nums.append(nums[0])
                del nums[0]
            else:
                del nums[0]
        return len(nums)

* 참고 링크 : https://bortfolio.tistory.com/124

 C++ 코드

 

C ++ code

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int count = 0;
        for(int i = 0; i < nums.size(); i++){
            if (nums[i] != val){
                nums[count++] = nums[i];
            }
        }
        return count;
    }
};

* 참고 링크 : https://egbert-yu-ting.github.io/posts/1afffcb4/

https://lessbutbetter.tistory.com/entry/LeetCodeEasyC%EB%AC%B8%EC%A0%9C%ED%92%80%EC%9D%B4-27-Remove-Element

 출처

 

https://leetcode.com/problems/remove-element/

반응형
2022-01-14 06:57:16
반응형

Valid Parentheses

 

 문제 설명

 

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

 

 제한 사항

 

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.

 

 입출력 예

 

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

 

 

 Python 코드

 

Python code 

class Solution:
  def isValid(self, s: str) -> bool:
      stack = []
      dic = {'(':')',
             '{':'}',
             '[':']'
            }

      for char in s:
          if char in dic.keys():
              stack.append(char)

          elif stack == [] or char != dic[stack.pop()] :
              return False

      return stack ==[]

 

* 참고 링크 : https://chaerim-kim.github.io/data%20structures%20and%20algorithms/ValidParentheses/

class Solution:
    def isValid(self, s: str) -> bool:
        stack=[]
        brackets={'}':'{',')':'(',']':'['}
        for bracket in s:
            if bracket in brackets.values(): #Opening bracket 
                stack.append(bracket)
            else:# Closing bracket
                if stack and brackets[bracket]==stack[-1] :  
                    stack.pop()
                else: 
                    return False
        
        if stack:
            return False
        return True

* 참고 링크 : https://velog.io/@kgh732/Python-%EC%9C%BC%EB%A1%9C-%ED%91%B8%EB%8A%94-Leetcode20.-Valid-Parentheses

class Solution: 
	def isValid(self, s: str) -> bool: 
    	s_list = list(s)
        
        answer = True 
        
        stack = [] 
        
        for s in s_list: 
        	if s == '[' or s == '(' or s == '{': 
            	stack.append(s) 
            elif len(stack) != 0: 
            	if (s == ']' and stack[-1] == '[') or (s == '}' and stack[-1] == '{') or (s == ')' and stack[-1] == '('): 
                	stack.pop() 
                else: 
                    answer = False 
                    break 
            else: 
            	answer = False 
                break 
                
        if len(stack) != 0: 
        	answer = False 
        return answer

* 참고 링크 : https://somjang.tistory.com/entry/leetCode-20-Valid-Parentheses-Python

 

C++ 코드

 

C ++ code

class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        
        for(int i = 0; i < s.size(); i++) {
            if(s.at(i) == '{' || s.at(i) == '(' || s.at(i) == '[')      st.push(s.at(i));
            else {
                if(st.empty())      return false;
                else {
                    if((s.at(i) == '}' && st.top() != '{') || (s.at(i) == ')' && st.top() != '(') 
                        || (s.at(i) == ']' && st.top() != '['))
                            st.push(s.at(i));
                    else    st.pop();
                }
            }   
        }
        
        return st.empty();
    }
};

* 참고 링크 : https://m.blog.naver.com/tac1994/221839649888

 

 출처

 

https://leetcode.com/problems/valid-parentheses/submissions/

반응형
2022-01-14 06:47:41
반응형

Palindrome Linked List

 

 문제 설명

 

Given the head of a singly linked list, return true if it is a palindrome.

 

 제한 사항

 

  • The number of nodes in the list is in the range [1, 105].
  • 0 <= Node.val <= 9

 

 입출력 예

 

Example 1:

Input: head = [1,2,2,1]
Output: true

 

Example 2:

Input: head = [1,2]
Output: false

 

 Python 코드

 

Python code 

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        val_list = []
        curr = head
        while curr:
            val_list.append(curr.val)
            curr = curr.next
        return val_list == val_list[::-1]

 

* 참고 링크 : https://ceuity.tistory.com/12

https://velog.io/@jayb/LeetCode-234.Palindrome-Linked-List%ED%8C%B0%EB%A6%B0%EB%93%9C%EB%A1%AC-%EC%97%B0%EA%B2%B0-%EB%A6%AC%EC%8A%A4%ED%8A%B8

 C++ 코드

 

C ++  code

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        ListNode *slow = head, *fast = head, *prev, *temp;
        while (fast && fast->next)
            slow = slow->next, fast = fast->next->next;
        prev = slow, slow = slow->next, prev->next = NULL;
        while (slow)
            temp = slow->next, slow->next = prev, prev = slow, slow = temp;
        fast = head, slow = prev;
        while (slow)
            if (fast->val != slow->val) return false;
            else fast = fast->next, slow = slow->next;
        return true;
    }
};

 

* 참고 링크 : https://dev.to/seanpgallivan/solution-palindrome-linked-list-5721

 

 출처

 

https://leetcode.com/problems/palindrome-linked-list/submissions/

반응형
2022-01-13 23:35:41
반응형

Single Number

 

 문제 설명

 

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

You must implement a solution with a linear runtime complexity and use only constant extra space.

 

 제한 사항

 

  • 1 <= nums.length <= 3 * 104
  • -3 * 104 <= nums[i] <= 3 * 104
  • Each element in the array appears twice except for one element which appears only once.

 

 입출력 예

 

Example 1:

Input: nums = [2,2,1]
Output: 1

Example 2:

Input: nums = [4,1,2,1,2]
Output: 4

Example 3:

Input: nums = [1]
Output: 1

 

 Python 코드

 

Python code 

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        answer = 0
        for i in nums:
            answer = answer ^ i
        return answer
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        cnt_dict = Counter(nums) 
        items = cnt_dict.items()
        
        for key, val in items:
            if val == 1:
                answer = key
                break
                
        return answer

* 참고 링크 : https://airsbigdata.tistory.com/89

 

 C++ 코드

 

C ++ 100% 0ms code

nt singleNumber(int a[], int n) {
     //xor all numbers, the left over number would be the non repeated one
     // since the equl numbers cancel out each others bits
     int num = 0;
     for (int i = 0; i < n; ++i) {
         num ^= a[i];
     }
     return num;
    }

* 참고 링크 : https://leetcode.com/problems/single-number/discuss/43237/4-lines-of-c%2B%2B-solution

 

 출처

 

https://leetcode.com/problems/single-number/

반응형