알고리즘문풀 with SWIFT/LeetCode

swift ) LeetCode - 1. Two Sum

유사앱등이 2022. 5. 29. 01:11

 

두 가지 코드 작성

 

 

1. 브루트포스

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
	for i in 0..<nums.count {

		if let j = nums.lastIndex(of: target - nums[i]) {
			if i != j {
				return [i,j]
			}
		}

	}
	return []
}

for문 중첩 안하려고 해봐도..

결국은 for문과 똑같은 로직이고, 오래 걸림

 

 

2. 해시테이블 이용

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
	var hashTable = [Int:Int]()
	for i in 0..<nums.count {
		let diff = target - nums[i]
		if hashTable[diff] != nil {
			return [i, hashTable[diff]!]
		}
		hashTable[nums[i]] = i
	}
	return []
}

 

나름대로 만족