샘성의 iOS 개발 일지

[Implementation] Apple and Orange 본문

Algorithm/HackerRank

[Implementation] Apple and Orange

SamusesApple 2023. 5. 12. 13:41
728x90

문제 설명:

  Sam's house has an apple tree and an orange tree that yield an abundance of fruit. Using the information given below, determine the number of apples and oranges that land on Sam's house.

In the diagram below:

  • The red region denotes the house, where s is the start point, and t is the endpoint. The apple tree is to the left of the house, and the orange tree is to its right.
  • Assume the trees are located on a single point, where the apple tree is at point a, and the orange tree is at point b.
  • When a fruit falls from its tree, it lands d units of distance from its tree of origin along the x-axis. *A negative value of d means the fruit fell d units to the tree's left, and a positive value of d means it falls d units to the tree's right. *

Given the value of d for m apples and n oranges, determine how many apples and oranges will fall on Sam's house (i.e., in the inclusive range [s, t] )?

 

 

 

 

 

내 풀이:

func countApplesAndOranges(s: Int, t: Int, a: Int, b: Int, apples: [Int], oranges: [Int]) -> Void {
    // 사과가 떨어진 좌표 매핑, [s...t] 범위 안에 속한 좌표만 필터하여 배열에 담기
    var appleArray = apples.map { $0 + a }.filter { apple in
    if apple >= s, apple <= t {
        return true
    } else { 
        return false 
        }
    }
    // 오렌지가 떨어진 좌표 매핑, [s...t] 범위 안에 속한 좌표만 필터하여 배열에 담기
    var orangeArray = oranges.map { $0 + b }.filter { orange in 
        if orange >= s, orange <= t {
            return true
        } else {
            return false
        }
    }
    print(appleArray.count)
    print(orangeArray.count)
}

 

 

 

 

 

 

회고:

  처음엔 for loop를 사용하여 풀었으나, 시간 초과로 통과하지 못했다.

// 맨 처음 풀이
func countApplesAndOranges(s: Int, t: Int, a: Int, b: Int, apples: [Int], oranges: [Int]) -> Void {
    var appleResult = 0
    var orangeResult = 0
    var appleArray = apples.map { $0 + a }
    var orangeArray = oranges.map { $0 + b }
    for spot in s...t {
        for apple in appleArray {
            if spot == apple {
                appleResult += 1
            }
        }
        for orange in orangeArray {
            if spot == orange {
                orangeResult += 1
            }
        }
    }
    print(appleResult)
    print(orangeResult)
}

 for loop문을 중첩했으니 시간 복잡도가 더욱 가중되어 시간초과가 났던 것 같다. 

728x90

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

[Implementation] Between Two Sets  (0) 2023.05.14
[Implementation] Number Line Jumps  (0) 2023.05.12
[Implementation] Grading Students  (0) 2023.05.12
[Warm Up] Time Conversion  (0) 2023.05.11
[Warm Up] Birthday Cake Candles  (0) 2023.05.11