https://leetcode.com/problems/create-target-array-in-the-given-order/

 

Create Target Array in the Given Order - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 풀이를 하자면, nums와 index들이 주어지고

해당 index에 값을 넣어서 배열을 만들어 주면 되는 간단한 문제!!

 

근데, 생각보다 쉽게 풀렸다?

 

왜냐면, result를 초기화하게 되면 인덱스 값이 이미 존재한지 몰랐다....!

 

그래서, result를 0으로 nums의 갯수로 초기화하였는데, 그럴 필요가 없었다. 

이 작업을 하면 0을 없애야하는 추가 작업도 해야하고... 배웠다!

 

생각해보니깐, 이 문제에서만 통한다.

 

테스트 케이스를 보니깐,

갑자기 이상 인덱스가 100으로 가지 않는다.

점점 숫자가 커진다. 오름차순 정렬이기 때문에 비어있는 인덱스가 없기 떄문에 괜찮았던 것이다.

 

 

class Solution {
    func createTargetArray(_ nums: [Int], _ index: [Int]) -> [Int] {
        var result: [Int] = []
        //var result = Array(repeating:0,count:nums.count)
        
        for i in 0..<nums.count{
            result.insert(nums[i],at: index[i])
        }
        
        return result
        
    }
}

다른 고수분들의 풀이도 비슷해서 패스!

'Algorithm > Leetcode' 카테고리의 다른 글

Leetcode_Build an Array with Stack Operations  (0) 2022.07.01
Leetcode_Available Captures for Rook  (0) 2022.07.01
Leetcode_Water Bottles  (0) 2022.07.01
Leetcode_Distribute Candies to People  (0) 2022.06.30
Leetcode_Transpose Matrix  (0) 2022.06.30

https://leetcode.com/problems/build-an-array-with-stack-operations/

 

Build an Array With Stack Operations - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

문제 해설을 하면 이렇다.

target과 n이 주어진다. 

n은 list의 갯수를 결정한다.

 

그래서, target을 보고 비교를 한 다음에 Push 혹은 Pop을 선택한다.

이것을 배열로 저장한다음에 Return한다.

 

내가 간과한 바는 그것이다. Target과 List의 인덱스가 같다는 판단을 하였다.

 

그렇다면!! 어떻게 해야할까?

 

시뮬레이션을 돌려보자!!

 

이중 for문을 활용해 봤는데요.

 

일단, target과 list의 크기가 다름으로써, 조절을 해야하는 문제가 생기네요...

다른 고수님들은 list를 만들지 않고, i를 만들어서

한개씩 풀이하신 것같아요. 

class Solution {
    func buildArray(_ target: [Int], _ n: Int) -> [String] {
        
        var result:[String] = []
        var list:[Int] = []
 
        for i in 1...n{
            list.append(i)
        }
        
        for i in 0..<target.count{
            for j in i..<list.count{
                 
                if target[i] == list[j]{
                    result.append("Push")
                    break
                }else{
                    
                    if i >= target.count{
                        break
                    }else{
                        result.append("Push")
                        result.append("Pop") 
                        continue
                    }
                }
            }
        }
        
        return result

    }
}

 

어렴풋한 생각을 직접 구현으로 하는 것!! 

정말 중요한 것 같아요!!

 

이렇게 i,j를 두어서 직접 제어하는 것도 좋은 방식인것 같아요!!

jayantsogikar님의 풀이

func buildArray(_ target: [Int], _ n: Int) -> [String] {
    var i = 1
    var j = 0
    var res : [String] = []
    while(j < target.count && i <= n){
        if i == target[j]{
            j += 1
            i += 1
            res.append("Push")
        }
        else{
            i += 1
            res.append("Push")
            res.append("Pop")
        }
    }
    return res        
    }

yamironov님의 풀이

class Solution {
    func buildArray(_ target: [Int], _ n: Int) -> [String] {
        let c = target.count
        var i = Int(0), result = [String]()
        for x in 1...n {
            if target[i] == x {
                result.append("Push")
                i += 1
            } else {
                result.append("Push")
                result.append("Pop")
            }
            if i >= c { break }
        }
        return result
    }
}

 

 

'Algorithm > Leetcode' 카테고리의 다른 글

Leetcode_Create Target Array in the Given Order  (0) 2022.07.01
Leetcode_Available Captures for Rook  (0) 2022.07.01
Leetcode_Water Bottles  (0) 2022.07.01
Leetcode_Distribute Candies to People  (0) 2022.06.30
Leetcode_Transpose Matrix  (0) 2022.06.30

https://leetcode.com/problems/available-captures-for-rook/

 

Available Captures for Rook - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

문제 풀이를 하면,

 

Rock 같은 경우에는 상하좌우 채스판 끝까지 넘어 다닐 수 있다. 

그리고, 중간에 비숍을 만나면, 그만 움직어야하고

하나의 폰을 잡으면 이 방향에서 더이상 잡지 못한다.

 

그래서, 나는 일단 락의 위치를 저장한다음에 

왔다갔다하는 방식으로 풀이하고자 했다.

 

아래는 손코딩한 부분!! 점점 나아질것이다!!

 

class Solution {
    func numRookCaptures(_ board: [[Character]]) -> Int {
    
    var count:Int = 0
    var row:Int = 0
    var col:Int = 0
     // finding origin  
     for i  in 0..<board.count{
         for j in 0..<board[0].count{
             if board[i][j] == "R"{
                 row = i
                 col = j
             }
         }
     }
        
    // to left    
    for i in stride(from:row,to:0,by:-1){
        print("left")
        if board[i][col] == "B"{
            break
        }else if board[i][col] == "p"{
            count += 1
            break
        }
    }
   
   // to right
   for i in stride(from:row,to:board[0].count-1,by:1){
       print("right")
        if board[i][col] == "B"{
            break
        }else if board[i][col] == "p"{
            count += 1
            break
        }  
   }
      
   // to top
   for j in stride(from:col,to:0,by:-1){
       print("up")
        if board[row][j] == "B"{
            break
        }else if board[row][j] == "p"{
            count += 1
            break
        }  
       
   }
  // to bottom
   for j in stride(from:col,to:board.count-1,by:1){
       print("down")
        if board[row][j] == "B"{
            break
        }else if board[row][j] == "p"{
            count += 1
            break
        }       
   } 
        
    return count
}
}




print!


left
left
right
right
right
right
up
up
up
down

 

 

 

위로가는 함수가 제대로 작동하지 않는다....

stride 부분이 잘못되었다.

정확히는 stride부분에서 to: 이 부분을 -1로하여서 끝까지 돌려야하는데, 그러지 못했다.

 

무언가 문제가 어려운면 작은 단위부터 시뮬레이션 돌리는 것도 좋은 방식인 것같다.

   // to top
   for j in stride(from:row,to:0,by:-1){
       print("up")
       print(board[j][col])
        if board[j][col] == "B"{
            print("B")
            break
        }else if board[j][col] == "p"{
            count += 1
            print("ucount")
            break
        }else if board[j][col] == "."{
            print("blink")
            continue
        }  
       
   }
   
   //
   up
   R

수정 후

class Solution {
    func numRookCaptures(_ board: [[Character]]) -> Int {
    
    var count:Int = 0
    var row:Int = 0
    var col:Int = 0
     // finding origin  
     for i  in 0..<board.count{
         for j in 0..<board[0].count{
             if board[i][j] == "R"{
                 row = i
                 col = j
             }
         }
     }
    print(row,col)    
        
    // to left    
    for i in stride(from:col-1,to:-1,by:-1){
        print("left")
        if board[row][i] == "B"{
            break
        }else if board[row][i] == "p"{
            count += 1
            print("lcount")
            break
        }else{
            continue
        }
    }
   
   // to right
   for i in stride(from:col,to:board[0].count,by:1){
       print("right")
        if board[row][i] == "B"{
            break
        }else if board[row][i] == "p"{
            count += 1
            print("rcount")
            break
        }else{
            continue
        }
   }
      
   // to top
   for j in stride(from:row-1,to:-1,by:-1){
       print(row)
       print("up")
       print(board[j][col])
        if board[j][col] == "B"{
            print("B")
            break
        }else if board[j][col] == "p"{
            count += 1
            print("ucount")
            break
        }else if board[j][col] == "."{
            print("blink")
            continue
        }  
       
   }
  // to bottom
   for j in stride(from:row,to:board.count,by:1){
       print("down")
        if board[j][col] == "B"{
            break
        }else if board[j][col] == "p"{
            count += 1
            print("dcount")
            break
        }else{
            continue
        }       
   } 
        
    return count
}
}

당연한게 없듯이, 하나하나 사고하면서 프로그래밍하는 것이 좋다는 생각을 했다.

 

다른 고수분들의 문제풀이를 보아도, 비슷한 것 같아서 넘기겠다!

'Algorithm > Leetcode' 카테고리의 다른 글

Leetcode_Create Target Array in the Given Order  (0) 2022.07.01
Leetcode_Build an Array with Stack Operations  (0) 2022.07.01
Leetcode_Water Bottles  (0) 2022.07.01
Leetcode_Distribute Candies to People  (0) 2022.06.30
Leetcode_Transpose Matrix  (0) 2022.06.30

https://leetcode.com/problems/water-bottles/submissions/

 

Water Bottles - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

문제를 풀이 해볼까요?

일단, 쉽게 생각하면 이러한 문제입니다.

 

꽉찬 병이 있고 다 마십니다. 그러면 비어있는 병이 있을 테죠?

 

근데, 어떤 착하신분이 비어있는 병을 가져오면 새로운것으로 주신다고 합니다!!

 

그래서, 생각해보면 크게 우리는 꽉찬 병, 비어있는 병 중심에 사고를 해야합니다!

 

그렇다면, 문제대로 손코딩을 해보았는데요.

 

아래와 같은 흐름으로 진행됩니다.

 

15 -> 0  -> 3 -> 0 -> 1 -> 0 : 꽉찬 병

0 -> 15 -> 3 -> 6 -> 2 -> 3 : 빈 병

 

이것을 생각하시면서, 코드를 구현하면 됩니다.

 

일단, 저는 배열 사용이 편하기 때문에 result 배열을 사용해서 마지막에 reduce()를 할 것입니다.

 

그러면, 일단 result에 apped n을 해줍니다.

그리고, n은 비어있는 병이 될테니, empty라는 값에 누적해줍니다.

 

여기서 누적을 해줘야하는 이유는 병을 리필 받고 이전에 있는 비어있는 병이랑 합쳐야하기 때문이죠!

 

그다음에 n은 empty/numE 으로 empty는 empty%numE으로 정의를 해주면 마무리 됩니다.

 

class Solution {
    func numWaterBottles(_ numBottles: Int, _ numExchange: Int) -> Int {
        
        var numB = numBottles
        var numE = numExchange
        
        var empty = 0
        var result:[Int] = []
        
        while numB>0{
            
            result.append(numB)
            empty += numB
            numB = empty/numE
            empty = empty%numE
        }
        return result.reduce(0,+)
    }
}

 

다른 고수님의 풀이를 봐볼까요? 어떻게 기상천외하게 작성하셨는지 궁금합니다 ㅎㅎ

 

이 분은 저처럼 Empty라는 값을 따로 정의하지 않았습니다.

 

그리고, numBottles>=numExchange를 조건으로 while하셨군요.

 

그리고  balance 를 numB%numE에 나머지를 대입하시고 

 

res에서 활용하시는 방향으로 가셨네요!!

 

재미있게 하셨네요, 깔끔하게!

class Solution {
    func numWaterBottles(_ numBottles: Int, _ numExchange: Int) -> Int {
        var bottles = numBottles
        var numBottles = numBottles
        while(numBottles>=numExchange){
            let balance = numBottles%numExchange
            let res=(numBottles-balance)/numExchange
            numBottles=balance+res
            bottles+=res
        }
        return bottles
    }
}

'Algorithm > Leetcode' 카테고리의 다른 글

Leetcode_Build an Array with Stack Operations  (0) 2022.07.01
Leetcode_Available Captures for Rook  (0) 2022.07.01
Leetcode_Distribute Candies to People  (0) 2022.06.30
Leetcode_Transpose Matrix  (0) 2022.06.30
Leecode_Flipping an Image  (0) 2022.06.30

https://leetcode.com/problems/distribute-candies-to-people/

 

Distribute Candies to People - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

문제 풀이를 시작해 볼께요!!

 

캔디가 있고 사람이 있습니다.

 

캔디가 7개가 있고 사람이 4명이 있다고 했을때,

 

첫번째 사람은 1개, 두번째 사람은 2개, 세번째 사람은 3개 네번 째 사람은 1개를 받게 됩니다.

 

여기서, 네번째 사람은 왜 1 개를 받냐면, 캔디가 7개 밖이 없기 떄문입니다.

 

그렇다면, 여기서 얻을 수 있는 힌트는 

 

캔디의 갯수로 while을 수행하고 캔디의 갯수가 0이 되면 마무리 되는 로직을 생각할 수 있습니다.

 

구체적으로, 총 두가지 경우에수가 생기겠죠?

중간에 Candy가 없어지는 경우 Candy가 있는 경우를 if로 분기로 나누면 될것같아요.

 

처음으로는, Candy가 있는 경우를 생각해보아요!

 

A B C D

1 2 3 ~ 

이렇게 1개 씩 추가하면서 캔디를 줄 수 있을까요??

주는 캔디를 n 이라고 하고 한 사람에게 주는 캔디를 n + 1라고 

하면 될까요?

 처음에 n = 0 으로 설정하구요!

오케이 그러면 

allocation[n % num_people]  += n + 1 

이라고 생각하면 될까요?

 

그런다음, 캔디를 줬으니깐 갯수에서 빼야겠죠?

canndies -= (n + 1)

 

그리고 n += 1 을 하면 점점 증가하겠죠!!

 

오케이 이제 전반적인 아이디어는 정리가 되었는데,

 

이제는 진행 중간에 캔디가 다 없어질때에요!!

 

candies = 7

A B C D

1 2 3

이것을

 

candies - (n + 1) < 0 

 1 - (6) < 0{

 allocation[n % num_people] += candies

 candies = 0

}

으로 마무리하면 됩니다.

 

이제, 위의 내용을 논리적으로 맞추기만 하면 됩니다!!

class Solution {
    func distributeCandies(_ candies: Int, _ num_people: Int) -> [Int] {
        var candies = candies
        var allocation: [Int] = Array(repeating: 0, count: num_people)
        var n = 0
        while candies > 0 {
            if candies - (n + 1) < 0 {
                allocation[n % num_people] += candies
                candies = 0
            } else {
                allocation[n % num_people] += n + 1
                candies -= (n + 1)
            }
            n += 1
        }
        return allocation
    }
    
}

'Algorithm > Leetcode' 카테고리의 다른 글

Leetcode_Available Captures for Rook  (0) 2022.07.01
Leetcode_Water Bottles  (0) 2022.07.01
Leetcode_Transpose Matrix  (0) 2022.06.30
Leecode_Flipping an Image  (0) 2022.06.30
Leetcode_Baseball Game  (0) 2022.06.30

https://leetcode.com/problems/transpose-matrix/

 

Transpose Matrix - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

 

풀이를 해보자구, 어디에서 막히는 지!!

 

일단, 문제 파악 자체는 오래 걸리지 않았어!! 

 

어떻게 구성을 할까를 고민을 많이 해봤어!!

 

일단, 간단히 설명하면,

 

2  4  -1

-10 5 11 

18 -7 6

 

이 것이 주어지면, y = -x 방향으로 전환을 해주면 되거든!!

 

2  -10 18

4  5  -7

-1 11 6 

이렇게 말이죠!! 

 

그러면, 이제 구성을 어떻게 할까 생각을 해봤어요!!

 

Slice하는 방식

인덱스로 해결하는 방법

 

나는 인덱스로 해결하고자하였다.

근데, 어디서 막혔나면, 1,4,7를 추가 하였다.... 근데 이것을 어떻게 하면 효율적으로 할지 아이디어가 떠오르지 않기에 고수님들의 코드를 보았따.

class Solution {
    func transpose(_ matrix: [[Int]]) -> [[Int]] {
        
        var flatArr = matrix.flatMap{$0}
        var result: [[Int]] = []
        
        for i in 0..<flatArr.count{
            if i.isMultiple(of:matrix.count){
               result.append([flatArr[i]])
            }
          
        }
        print(result)
        
        return []   
    }
}

상기에서 하기와 같이 수정했어!

class Solution {
    func transpose(_ matrix: [[Int]]) -> [[Int]] {
        
        var row = matrix.count
        var col = matrix[0].count
        var result: [[Int]] = []
        
        for i in 0..<col{
          var resultRow:[Int] = []
            for j in 0..<row{
                resultRow.append(matrix[j][i])
            }
           result.append(resultRow) 
        }
        
        return result

    }
}

 

 

snehakasetty님의 해결방안인데, 내가 머리속으로 어렴풋이 그렸던 코드가 이것이다.

 

A라는 행렬을 새로 만든 행렬에 삽입하자 라는 생각이 포인트!!!

나는 swapt 할 생각만 했었다.

c[j][i] = A[i][j] !! 이부분이 핵심적인 내용!!

func transpose(_ A: [[Int]]) -> [[Int]] {
    
    if(A.count == 0){
        return A
    }
    
    var c = Array(repeating: Array(repeating: 0, count: A.count), count: A[0].count)

    for i in 0 ..< A.count {
        for j in 0 ..< A[0].count {
            c[j][i] = A[i][j]
        }
    }
    return c
}

 

 

아래분의 해설도 볼만 하다.

전달 받은 행렬의 행과 렬의 갯수를 rowCount, colCount라고 정의를 내려 주었고 

 

collum{

row 

}

 

이런식으로 진행했네!!

 

이것이랑 같이 보면 좋을 것 같아서 첨부함.

var col = 7
var row = 3


for i in 0..<row{
    for j in 0..<col{
        print("*",terminator:"")
    }
    print("")
}

print("----------------------------")

for i in 0..<col{
    for j in 0..<row{
        print("*",terminator:"")
    }
    print("")
}
*******
*******
*******
----------------------------
***
***
***
***
***
***
***

 

for문을 잘보면 col이랑 row의 위치를 변경해서 넣어버렸네 좋은 선택인듯!!

그리고 resultRow라는 것도 함수내에 사용되고 초기화해야하니깐, 함수 내에 정의내린것도 좋다!!!

class Solution {
    func transpose(_ matrix: [[Int]]) -> [[Int]] {
        var result = [[Int]]()

        let rowCount = matrix.count
        let colCount = matrix[0].count

        for colId in 0..<colCount {
            var resultRow = [Int]()
            for rowId in 0..<rowCount {
                resultRow.append(matrix[rowId][colId])
            }
            result.append(resultRow)
        }

        return result
    }
}

'Algorithm > Leetcode' 카테고리의 다른 글

Leetcode_Water Bottles  (0) 2022.07.01
Leetcode_Distribute Candies to People  (0) 2022.06.30
Leecode_Flipping an Image  (0) 2022.06.30
Leetcode_Baseball Game  (0) 2022.06.30
Leetcode_Robot-return-to-origin  (0) 2022.06.30

https://leetcode.com/problems/flipping-an-image/

 

Flipping an Image - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

풀이를 하면 이렇다.

 

2차 배열이 주어지면, 이것을 수평방향으로  flip하고 invert해라!!

 

0 -> 1로 1-> 0으로!!

오케이!!

됬다.나는 수평으로 flip은 함수를 찾아보았지만, 찾지 못했다. 그리하여, reversed로 해결하기로 했다.

이 다음이 문제다. 

Inverse를 어떻게 할 것인가????

일단. 나는 for문을 활용해서 하나하나 찾는 방향으로 갔다. 다른 고수님들의 해결책을 봐보자!!.

class Solution {
    func flipAndInvertImage(_ image: [[Int]]) -> [[Int]] {
        var result: [[Int]] = []
        
        for i in 0..<image[0].count{
            result.append(image[i].reversed())
        }
        
        for j in 0..<result[0].count{
            if result[j].contains(1){
                result[j].swapAt(1,0)
            }else{
                result[j].swaptAt(0,1)
            }
        }
        
        print(result)
        
        return[[]]
    }
}

 

이 해결책은 swapt이 method로 없고 인덱스를 넣는 곳이기 때문에 적절한 함수 사용이 아니다.

Line 13: Char 27: error: value of type '[Int]' has no member 'swaptAt' in solution.swift
                result[j].swaptAt(0,1)
                ~~~~~~~~~ ^~~~~~~

 

 

 

Arkadiy Grigoryanc님의 풀이인데,이럴때에 고차함수를 사용해야하구나를 느끼게 해준 고마운 풀이법인다.

 

Reverse를 해야하고, 하나 하나 접근해야한다. 단순하게 접근하면 된다. !!

return A.map{ $0.reversed().map{$0 == 0 ? 1 : 0}}

Good!!

class Solution {
    func flipAndInvertImage(_ A: [[Int]]) -> [[Int]] {
        return A.map { $0.reversed().map { $0 == 0 ? 1 : 0 } }
    }
}

 

 

wds8807님의 풀이를 보면 아래와 같다.

전형적인 좋은 풀이이다. 

for문으로 돌려서 Reversed를 했고 이것을 다시 for문으로 확인하고 0과 1를 교체하는 프로그램을 했다.

 

class Solution {
    func flipAndInvertImage(_ A: [[Int]]) -> [[Int]] {
      var answer = A
      for i in 0..<answer.count {
        answer[i].reverse()
        for j in 0..<answer[i].count {
          answer[i][j] = answer[i][j] == 1 ? 0 : 1
        }
      }

      return answer
    }
}

성능을 두개 비교해봤는데, 비슷했다.

'Algorithm > Leetcode' 카테고리의 다른 글

Leetcode_Distribute Candies to People  (0) 2022.06.30
Leetcode_Transpose Matrix  (0) 2022.06.30
Leetcode_Baseball Game  (0) 2022.06.30
Leetcode_Robot-return-to-origin  (0) 2022.06.30
Leetcode_fizz-buzz  (0) 2022.06.30

https://leetcode.com/problems/baseball-game/

 

Baseball Game - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

풀이를 해봅시다.

일단, 이러한 문제이에요.

게임을 하는데, 이상한 룰이 있어요.

C,D,+와 같은 룰이죠.

이 게임에서는 과거가 미래까지 영향력을 많이 주어요!

 

C는 바로 이전 게임의 점수를 초기화 시켜요!!

D는 바로 이전 게임의 점수를 두배를 만들어 주고여. 아 여기서 제곱이 아니에요.

+는 이이전 수와 이전수를 더해요!! 

그리고 그냥 Int는 점수로 쳐줘요!!

이렇게 해서,

 

아래와 같이 Switch 문으로 작성을 해보왔는데요!!

 

아직 타입을 확실히 이해하지 못한 것같아요!!

그래서 확실히 result를 [Int]로 확실히 찍고!!!!!!

append()를 해줍니다.

 

그런데... 여기서 큰 실수가 있죠?

뭐냐면, forEach 문의 장점은 간략하고 신속하게 문제를 해결할 수 있는 것이죠!!

 

근데, 아쉽게도 세세한 상황을 다루지는 못해요.

 

이런것이 설계 미스인것같아요!!

 

앞으로는 조금 다뤄야할 것이 많다면, 

i 인덱스를 사용하는 것이 더 빠를 수도 있다는 것을 느껴요!

 

다른 고수님들의 풀이를 봐볼까요?

class Solution {
    func calPoints(_ ops: [String]) -> Int {
        
        var result:[Int] = []
        
        ops.forEach{ op in 
             switch op{
                 case "C": result.removeLast()
                 case "D": result.append(result.first! * 2)
                 case "+": result.append(result.first! + result.last!)
                 default: 
                 result.append(Int(op)!)
             }       
             print(result)
        }   
        
        return result.reduce(0,+)
    }
}

 

 

Prabhat_Tripathi 님의 풀이를 가져와 봤는데요,
이 분은 for문과 if문의 조합을 사용하셨네요!!
나쁘지 않아요!! 

이 부분을 잘하신것 같아요!!

인덱스 관리하는 부분을 잘하셨어요!!

[scoreArray.count - 2] + [scoreArray.count - 1]

 

그리고 마지막에 삼항 연산자로 연결해서 비워있을 수도 있으니깐?

isEmpty를 체크해서 비워있다면 0!! 

 

이부분도 잘하신 것같아요.

 

다른 분들도 대부분 비슷하게 해서 이번에는 한개만 후기해요!

class solution {
		var scoreArray = [Int]()
		for i in 0..<ops.count {
			if ops[i] == "C" {
				scoreArray.removeLast()
			} else if ops[i] == "D" {
				scoreArray.append(scoreArray.last! * 2)
			} else if ops[i] == "+" {
				scoreArray.append(scoreArray[scoreArray.count - 2] + scoreArray[scoreArray.count - 1])
			} else {
				scoreArray.append(Int(ops[i])!)
			}
		}
		return scoreArray.isEmpty ? 0 : scoreArray.reduce(0, +)
}

 

 

'Algorithm > Leetcode' 카테고리의 다른 글

Leetcode_Transpose Matrix  (0) 2022.06.30
Leecode_Flipping an Image  (0) 2022.06.30
Leetcode_Robot-return-to-origin  (0) 2022.06.30
Leetcode_fizz-buzz  (0) 2022.06.30
Leetcode_Add digits  (0) 2022.06.30

https://leetcode.com/problems/robot-return-to-origin/

 

Robot Return to Origin - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

문제를 풀이하면 이렇다!

 

시작 점이랑 도착 점이랑 같으면 된다.!!

 

그리고, 움직임들이 주어짐!!

 

그렇다면, 생각을 해볼까요?

 

UP, DOWN, RIGHT, LEFT 가 주어지는데, 

Up은 y+1 

Down은 y-1

Right는 x+1

Left는 x-1

이라고 해석이 가능해지고

 

Switch 문으로 해결해보자!!

 

forEach라는 고차원 함수를 사용했다. 그런다음에 return 에서 (0,0) 이라면 참을 반환해라 로 마무리를 했습니다.

class Solution {
    func judgeCircle(_ moves: String) -> Bool {
        
        var x = 0
        var y = 0

    
        moves.forEach{ move in 
            switch move{
                case "R": x += 1
                case "L": x -= 1
                case "U": y += 1
                case "D": y -= 1     
                default: break
            }
            
        }
        
        return x == 0 && y == 0
    }
}

 

다른 고수분들의 답안을 봐보자.

Hashhhhhh 좋다.

Switch 문보다 이런 Hash도 좋다.

subzTrop
class Solution {
    func judgeCircle(_ moves: String) -> Bool {
        var moves = Array(moves)
        var mapping: [Character: Int] = ["U": 1, "D": -1, "L": -1, "R": 1]
        
        var udtotal = 0
        var lrtotal = 0

        
        for move in moves {
            if move == "U" || move == "D" {
                udtotal += mapping[move]!
            } else {
                lrtotal += mapping[move]!
            }
        }
        
        return udtotal == 0 && lrtotal == 0
    }
}

 

이것도 괜찮은 것 같아서 가져왔다. 하나의 Hash 보다는 하나하나 나누어서 정의 내리고 해결하는 것도 굿.

 

iCodeForExcellence
class Solution {
    func judgeCircle(_ moves: String) -> Bool {
        if (moves.isEmpty) {return true}
        var left = 0
        var right = 0
        var up = 0
        var down = 0
        var result = Array(moves)
        for i in result {
            if(i == "U") {up += 1}
            if(i == "D") {down += 1}
            if(i == "L") {left += 1}
            if(i == "R") {right += 1}
        }
        return ((left - right == 0) && (up - down == 0))
    }
    
}

'Algorithm > Leetcode' 카테고리의 다른 글

Leecode_Flipping an Image  (0) 2022.06.30
Leetcode_Baseball Game  (0) 2022.06.30
Leetcode_fizz-buzz  (0) 2022.06.30
Leetcode_Add digits  (0) 2022.06.30
Leetcode_Add Strings  (0) 2022.06.30

https://leetcode.com/problems/fizz-buzz/

 

Fizz Buzz - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

문제를 풀이해보자.

 

Fizz와 Buzz를 울리는 문제인데,

 

3의 배수일때에는 Fizz

5의 배수일때에는 Buzz 

15의 배수일대에는FizzBuzz를 울러야한다.

 

고민을 했다..... 배수라는 것을 어떻게 체크할까?

문서에다가 검색을 해보았다.

isMultiple(of:)!! 찾았다.

Instance Method
isMultiple(of:)
Returns true if this value is a multiple of the given value, and false otherwise.
print(1.isMultiple(of:3)) //false
print(15.isMultiple(of:3)) //true
print(3.isMultiple(of:15)) //false

신기합니다!!

그래서, 이 함수를 이용해서 해당 String을 append하는 방식으로 문제를 해결했습니다.

 

 

class Solution {
    func fizzBuzz(_ n: Int) -> [String] {
        var result: [String] = []
        
        for i in 1...n{
            
            if i.isMultiple(of:15){
                result.append("FizzBuzz")
                continue
            }
            if i.isMultiple(of:3){
                result.append("Fizz")
                continue
            }
            if i.isMultiple(of:5){
                result.append("Buzz")
                continue
            }

            
            result.append("\(i)")
            
        }    
        
        return result
    }
}

다른 고수님들의 풀이를 같이 볼까요?

 

다른 고수님들도 비슷하게 풀이하셨네요!! Leetcode에서는 이렇게 푼것을 naive하게 풀었다고 표현하네요 !!

class Solution {
    func fizzBuzz(_ n: Int) -> [String] {
        var result = [String]()
        
        for i in 1...n{
            if i % 3 == 0 && i % 5 == 0{
                result.append("FizzBuzz")
            }else if i % 3 == 0 {
                result.append("Fizz")
            }else if i % 5 == 0{
                result.append("Buzz")
            }else{
                result.append("\(i)")
            }
        }
        
        return result
    }
}

'Algorithm > Leetcode' 카테고리의 다른 글

Leetcode_Baseball Game  (0) 2022.06.30
Leetcode_Robot-return-to-origin  (0) 2022.06.30
Leetcode_Add digits  (0) 2022.06.30
Leetcode_Add Strings  (0) 2022.06.30
Leetcode_convert-1d-array-into-2d-array  (0) 2022.06.29

+ Recent posts