알고리즘
[Swift 알고리즘] - Max Consecutive Ones (연속되는 숫자 1의 최대값 구하기)
Peppo
2022. 5. 10. 10:53
728x90
https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3238/
Explore - LeetCode
LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.
leetcode.com
내 풀이
func findMaxConsecutiveOnes(_ nums: [Int]) -> Int {
var count = 0
var saveOneCount: [Int] = []
nums.map {
if $0 == 1 {
count += 1
saveOneCount.append(count)
} else {
count = 0
saveOneCount.append(count)
}
}
return saveOneCount.max()!
}
//findMaxConsecutiveOnes([1,1,0,1,1,1])
findMaxConsecutiveOnes([0])
풀이
더보기
1. 고차함수 map 을 사용해서 배열중 1이 있으면 count를 1 증가 시키고, saveOneCount 배열에 넣습니다.
배열중 0이 있으면 count를 0으로 초기화 시킵니다.
2. 배열이 다 돌면 saveOneCount에 있는 숫자중 가장큰 숫자를 반환 합니다. max() 메소드 사용.
배운것
map()
기존 데이터를 변형하고자 할때 사용됩니다.
for - in 구문과 유사 하지만 아래와 같은 이점이 있습니다.
- 코드가 간결해집니다.
- 재사용 할 수 있습니다.
- 컴파일러 최적화 성능이 좋습니다.
예제
let numberArr = [1, 2, 3, 4]
let transformArr = numberArr.map { $0 * 2 } // 요소 처음부터 끝까지 2씩 곱하겠다!
print(transformArr)
// [2, 4, 6, 8]
max(_:_:)
값 들중 가장 큰 수를 반환 합니다.
예제
let numberArr = [1, 5, 10, 2, 3]
numberArr.max() // 최대값 반환
728x90