지난 공부기록/알고리즘 풀이

Python - Algorithm #12

hkl22 2024. 6. 28. 10:06

Python Algorithm

LeetCode

1816. Truncate Sentence

  • A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation).
    • For example, "Hello World", "HELLO", and "hello world hello world" are all sentences.
  • You are given a sentence s​​​​​​ and an integer k​​​​​​. You want to truncate s​​​​​​ such that it contains only the first k​​​​​​ words. Return s​​​​​​ after truncating it.
  • Constraints
    • 1 s.length 500
    • k is in the range [1, the number of words in s].
    • s consist of only lowercase and uppercase English letters and spaces.
    • The words in s are separated by a single space.
    • There are no leading or trailing spaces.
class Solution:
    def truncateSentence(self, s: str, k: int) -> str:
        # split, slicing, join
        word_list = s.split(" ")
        return " ".join(word_list[:k])
class Solution:
    def truncateSentence(self, s: str, k: int) -> str:
        l = s.split()[:k]
        return " ".join(l)

2717. Semi-Ordered Permutation

  • You are given a 0-indexed permutation of n integers nums.
  • A permutation is called semi-ordered if the first number equals 1 and the last number equals n. You can perform the below operation as many times as you want until you make nums a semi-ordered permutation:
    • Pick two adjacent elements in nums, then swap them.
  • Return the minimum number of operations to make nums a semi-ordered permutation.
  • A permutation is a sequence of integers from 1 to n of length n containing each number exactly once.
  • Constraints
    • 2 nums.length == n 50
    • 1 nums[i] 50
    • nums is a permutation.
class Solution:
    def semiOrderedPermutation(self, nums: List[int]) -> int:
        # 1. 1과 n의 위치 구하기
        # 2. 1이 n보다 앞에 있을 경우, 필요한 이동 수 구하기
        # 3. 1이 n보다 뒤에 있을 경우, 필요한 이동 수 구하기
        first_index = nums.index(1)
        last_index = nums.index(len(nums))
        if first_index < last_index:
            answer = first_index + (len(nums) - 1 - last_index)
        else:
            answer = first_index + (len(nums) - 1 - last_index) - 1
        return answer
class Solution:
    def semiOrderedPermutation(self, nums: List[int]) -> int:
        n = len(nums)
        s, e = nums.index(1), nums.index(n)
        if s < e:
            return s + (n - 1) - e
        else:
            return s + (n - 2) - e

https://leetcode.com/problems/truncate-sentence/

https://leetcode.com/problems/semi-ordered-permutation/

 

'지난 공부기록 > 알고리즘 풀이' 카테고리의 다른 글

Python - Algorithm #14  (0) 2024.07.02
Python - Algorithm #13  (0) 2024.07.01
Python - Algorithm #11  (0) 2024.06.27
SQL - Algorithm #10  (0) 2024.06.24
SQL - Algorithm #9  (0) 2024.06.21