[LeetCode/Swift] 1번-TwoSome

kimdocs...📄·2022년 7월 22일

Algorithm

목록 보기
1/6
post-thumbnail

문제

https://leetcode.com/problems/two-sum/

접근 과정

  • 이중 반복문을 통해 배열 원소에 하나씩 접근해서 특정 원소값을 더해가며 target에 대한 if문을 실행한다.
  • 시간복잡도가 O(n2)이 나올것이 뻔하지만, 다른 방법은 아모른직다.. 공부해야지!!!

코드

class Solution {
    func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        for a in 0..<nums.count {
            for b in (a+1)..<nums.count {
                if target == nums[a] + nums[b] {
                    return [a, b]
                }
            }
        }
        return []
    }
}

처음에는

class Solution {
    func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        for a in 0...nums.count-1 {
            for b in 0...a {
                if a == b {
                    continue
                }
                if target == nums[a] + nums[b] {
                    return [a, b].sorted()
                }
            }
        }
        return [0, 0]
    }
}

이렇게 했으나, sorted()때문에 시간이 생각보다 많이 걸렸다.
정답의 0번째 인덱스가 1번째 인덱스보다 작으므로 b < a 조건을 먼저 염두해 두고 푸는게, 더 효과적이어보인다.

profile
👩‍🌾 GitHub: ezidayzi / 📂 Contact: ezidayzi@gmail.com

0개의 댓글