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

Python - Algorithm #59

hkl22 2024. 9. 27. 10:12

Python Algorithm

LeetCode

2057. Smallest Index With Equal Value

  • Given a 0-indexed integer array [nums], return the smallest index i of [nums] such that i mod 10 == nums[i], or -1 if such index does not exist.
  • x mod y denotes the remainder when x is divided by y.
  • Constraints
    • 1 nums.length 100
    • 0 nums[i] 9
class Solution:
    def smallestEqual(self, nums: List[int]) -> int:
        answer = -1
        # for, enumerate
        for i, num in enumerate(nums):
            # i mod 10 == nums[i] 조건 맞으면 i를 answer 지정 후 break
            if i % 10 == nums[i]:
                return i
        return answer
class Solution:
    def smallestEqual(self, nums: List[int]) -> int:
        for i in range(len(nums)):
            if i % 10 == nums[i]:
                return i
        return -1

2078. Two Furthest Houses With Different Colors

  • There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array [colors] of length n, where colors[i] represents the color of the iᵗʰ house.
  • Return the maximum distance between two houses with different colors.
  • The distance between the iᵗʰ and jᵗʰ houses is abs(i - j), where abs(x) is the absolute value of x.
  • Constraints
    • n == colors.length
    • 2 n 100
    • 0 colors[i] 100
    • Test data are generated such that at least two houses have different colors.
class Solution:
    def maxDistance(self, colors: List[int]) -> int:
        answer = 0
        # 2중 for문으로 모든 쌍 검사
        for i in range(len(colors)):
            for j in range(i+1, len(colors)):
                if colors[i] != colors[j]:
                    answer = max(answer, j-i)
        return answer
class Solution:
    def maxDistance(self, colors: List[int]) -> int:
        answer = 0
        for i in range(len(colors)):
            for j in range(i+1, len(colors)):
                if colors[i] != colors[j]:
                    answer = max(j - i, answer)
        return answer

https://leetcode.com/problems/smallest-index-with-equal-value/description/

https://leetcode.com/problems/two-furthest-houses-with-different-colors/

 

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

Python - Algorithm #61  (0) 2024.10.01
Python - Algorithm #60  (0) 2024.09.30
Python - Algorithm #58  (0) 2024.09.26
Python - Algorithm #57  (0) 2024.09.25
Python - Algorithm #56  (0) 2024.09.24