๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“š Coding Test

[LeetCode] 724. Find Pivot Index

by ํ‹ด๋”” 2022. 8. 1.
๋ฐ˜์‘ํ˜•

https://www.pexels.com/ko-kr/photo/4164418/

 

  • pivot ์ธ๋ฑ์Šค๋ž€ ์ธํ…์Šค์˜ ๋ชจ๋“  ์™ผ์ชฝ ์š”์†Œ์˜ ํ•ฉ๊ณผ ์˜ค๋ฅธ์ชฝ์˜ ๋ชจ๋“  ์š”์†Œ์˜ ํ•ฉ์ด ๊ฐ™์€ ์ง€์ ์˜ ์ธ๋ฑ์Šค
class Solution {
    func pivotIndex(_ nums: [Int]) -> Int {
        var rightSum = nums.reduce(0, +) - nums[0]
        var leftSum = 0

        if rightSum == leftSum {
            return 0
        }

        for index in 1..<nums.count {

            leftSum += nums[index - 1]
            rightSum -= nums[index]

            if leftSum == rightSum {
                return index // pivot index
            }
        }

        return -1
    }
}
var rightSum = nums.reduce(0, +) - nums[0]
  • ์–ด๋ ˆ์ด ์ „์ฒด ํ•ฉ์„ ๊ตฌํ•จ. ์ฒ˜์Œ ํ”ผ๋ด‡ ์ธ๋ฑ์Šค๋Š” ์–ด๋ ˆ์ด์˜ 0๋ฒˆ์งธ ์ธ๋ฑ์Šค -> ํ”ผ๋ด‡ ์ธ๋ฑ์Šค ๊ธฐ์ค€ ์™ผ์ชฝ ํ•ฉ, ์˜ค๋ฅธ ์ชฝ ํ•ฉ์„ ๊ตฌํ•ด์•ผ ํ•˜๋ฏ€๋กœ ์ „์ฒด ํ•˜์—์„œ ํ˜„์žฌ ์ธ๋ฑ์Šค ๊ฐ’์„ ๋นผ์คŒ
        if rightSum == leftSum {
            return 0
        }
  • ์ฒซ ๋ฒˆ์งธ ์ธ๋ฑ์Šค์—์„œ ์™ผ์ชฝ ํ•ฉ, ์˜ค๋ฅธ ์ชฝ ํ•ฉ์ด ๊ฐ™์€ ๊ฒฝ์šฐ ์ฒซ ๋ฒˆ์งธ ์ธ๋ฑ์Šค๊ฐ€ ํ”ผ๋ด‡ ์ธ๋ฑ์Šค ์ด๋ฏ€๋กœ 0์„ ๋ฆฌํ„ดํ•จ (์ธ๋ฑ์Šค 0์ด ํ”ผ๋ด‡ ์ธ๋ฑ์Šค)
  • ์ „์ฒด ํ•ฉ S์—์„œ ํ˜„์žฌ ํ”ผ๋ด‡ ์ธ๋ฑ์Šค ๊ฐ’ nums[0] ๋บ€ ๊ฐ’์ธ rightSum = S - nums[0] ๊ณผ leftSum (์ดˆ๊ธฐ ๊ฐ’ 0)์„ ๋น„๊ต
        for index in 1..<nums.count {

            leftSum += nums[index - 1]
            rightSum -= nums[index]

            if leftSum == rightSum {
                return index // pivot index
            }
        }
  • 0 ๋ฒˆ์งธ ์ธ๋ฑ์Šค๋ฅผ ๋น„๊ต ํ–ˆ์œผ๋ฏ€๋กœ 1 ๋ถ€ํ„ฐ ์ „์ฒด ๊ฐฏ์ˆ˜ - 1 ๋งŒํผ for๋ฌธ์„ ๋Œ๋ ค ๋ฐ˜๋ณตํ•จ
  • ์ด์ „ ํ”ผ๋ด‡ ๊ฐ’์„ leftSum์— ๋”ํ•ด ๊ฐ€๋ฉด ํ”ผ๋ด‡ ์ธ๋ฑ์Šค ๊ธฐ์ค€ ์™ผ์ชฝ ์–ด๋ ˆ์ด ํ•ฉ์„ ๊ตฌํ•  ์ˆ˜ ์žˆ์Œ
  • rightSum์€ ํ˜„์žฌ ํ”ผ๋ด‡ ์ธ๋ฑ์Šค ๊ฐ’์„ ๋นผ์ฃผ๋ฉด ๊ตฌํ•  ์ˆ˜ ์žˆ์Œ
  • ๋งŒ์•ฝ leftSum ๊ณผ rightSum์ด ๊ฐ™๋‹ค๋ฉด ํ”ผ๋ด‡ ์ธ๋ฑ์Šค ์ด๋ฏ€๋กœ ์ด๋ฅผ ๋ฆฌํ„ด
return -1
  • ๋งŒ์•ฝ ํ”ผ๋ด‡ ์ธ๋ฑ์Šค๊ฐ€ ์—†๋‹ค๋ฉด -1์„ ๋ฆฌํ„ดํ•˜๋ฉด ๋จ
class Solution {
    func pivotIndex(_ nums: [Int]) -> Int {
        var rightSum = nums.reduce(0, +)
        var leftSum = 0

        for index in 0..<nums.count {
            rightSum -= nums[index]
            
            if leftSum == rightSum {
                return index
            }
            
            leftSum += nums[index]
        }

        return -1
    }
}
  • for ๋ฌธ์„ 0 ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๊ฒŒ ํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด ๊ฐ„๋‹จํ•˜๊ฒŒ ์œ„์™€ ๊ฐ™์ด ํ•  ์ˆ˜ ์žˆ์Œ

 

 

์ฐธ๊ณ  ์‚ฌ์ดํŠธ ๋ฐ ๋„์„œ

https://leetcode.com/problems/find-pivot-index/solution/

 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€