LeetCode 1. Two Sum - Swift Solution

Problem

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


Problem Summary

Given an array of integers and a target, find the indices of two numbers that add up to the target. Return the indices in any order.


Solution

class Solution {
    func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        var answer: [Int] = []
        var dictionary: [Int: Int] = [:]
        for index in 0..<nums.count {
            let diff = target - nums[index]
            if let storedIndex = dictionary[diff] {
                answer = [storedIndex, index]
                break
            } else {
                dictionary[nums[index]] = index
            }
        }
        return answer
    }
}


This code implements the solution to the "two sum" problem. The function takes an array of integers and a target integer as inputs and returns the indices of two numbers in the array that add up to the target.


The function uses a dictionary to keep track of the indices of previously seen numbers. It iterates through the array and calculates the difference between the target and the current number. If the difference exists in the dictionary, it means that a pair of numbers exists that add up to the target. The function returns the indices of the current number and the difference.


If the difference does not exist in the dictionary, the current number is added to the dictionary with its index as the value. This is done so that the function can check for pairs that add up to the target later in the iteration.


Overall, this algorithm has a time complexity of O(n) since it only iterates through the array once. The space complexity is also O(n) since the dictionary can store up to n-1 key-value pairs.

댓글

이 블로그의 인기 게시물

What is Klaytn Network?

MVVM Pattern in Swift: A Step-by-Step Tutorial with Code Examples