샘성의 iOS 개발 일지

[Implementation] Migratory Birds 본문

Algorithm/HackerRank

[Implementation] Migratory Birds

SamusesApple 2023. 5. 17. 15:08
728x90

문제 설명:

 Given an array of bird sightings where every element represents a bird type id, determine the id of the most frequently sighted type. If more than 1 type has been spotted that maximum amount, return the smallest of their ids.

Example

arr = [1, 1, 2, 2, 3]

There are two each of types 1 and 2, and one sighting of type 3. Pick the lower of the two types seen twice: type 1.

Function Description

Complete the migratoryBirds function in the editor below.

migratoryBirds has the following parameter(s):

  • int arr[n]: the types of birds sighted

Returns

  • int: the lowest type id of the most frequently sighted birds
 

 

 

 

내 풀이:

func migratoryBirds(arr: [Int]) -> Int {
	// 같은 숫자 바로 바로 비교할 수 있도록 큰 순서대로 정렬
    let sortedArray = arr.sorted(by: >)
    var number = sortedArray[0]	// 시작 비교 숫자 세팅
    var numberCount = 0	// 해당 숫자가 몇개 존재하는지 카운트 할 변수
    var resultArray = [[Int]]() // [숫자, 갯수] 형태로 배열 담을 변수 생성
    for value in sortedArray {
    	// 비교할 숫자가 같다면 count + 1
        if number == value {
            numberCount += 1
        } else {
        	// 다르다면, resultArray에 [숫자, 갯수] 배열 append
            resultArray.append([number, numberCount])
            number = value	// 다음 숫자로 number 초기화
            numberCount = 0  // 카운팅 0으로 리셋
        }
    }
    // 갯수 많은 순서대로 정렬
    let sortedResultArray = resultArray.sorted { array1, array2 in
       array1[1] > array2[1] }
    // 가장 많은 갯수 뽑아서 담는 변수 (중복된 숫자 중 가장 작은 숫자를 뽑기 위함)
    let biggestCount = sortedResultArray[0][1]
    // 가장 많은 갯수를 가진 배열만 뽑아서 필터 -> 숫자 작은 순서대로 배열 재정렬 (sorted)
    let finalResult = sortedResultArray.filter { $0[1] == biggestCount }.sorted { array1, array2 in
        array1[0] < array2[0]
    }
    // 재정렬 된 결과 중, 첫번째 배열의 숫자 return
    return finalResult[0][0]
}

 

 

 

 

회고: 

  맨 처음엔, 이전 포스팅과 동일하게 for loop문을 중첩했지만 역시나 시간초과로 정답률 70%를 얻고 실패했다.

그래서 고민하다, 배열의 sorted를 여러번 사용하여 풀어보고 싶어 위의 해답이 나왔다. 변수도 많이 생성해야하고 코드가 전혀 깔끔하다는 생각이 들지 않아 아쉬움이 매우 많다.... 문제를 푸는것에 급급해서 어쩔 수 없나보다..

  순열과 조합에 대해 포스팅하면서, 관련 함수 만드는 것에 익숙해진 이후 코딩테스트 문제를 풀어나가는 것이 좋을 것 같다.

 

 

728x90

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

[Implementation] Sales by Match  (0) 2023.07.12
[Implementation] Divisible Sum Pairs  (0) 2023.05.17
[Implementation] Breaking the Records  (0) 2023.05.14
[Implementation] Between Two Sets  (0) 2023.05.14
[Implementation] Number Line Jumps  (0) 2023.05.12