LeetCode Two Sum

5月箴言html

住進布達拉宮,我是雪域最大的王。流浪在拉薩街頭,我是世間最美的情郎。—— 倉央嘉措算法

 

從本週起每週研究一個算法,並以swift實現之swift

001 -- Two Sum (兩數之和)數組

題幹英文版:安全

Given an array of integers, return indices of the two numbers such that they add up to a specific target.數據結構

You may assume that each input would have exactly one solution, and you may not use the same element twice.less

Example:函數

Given nums = [2, 7, 11, 15], target = 9,spa

Because nums[0] + nums[1] = 2 + 7 = 9,code

return [0, 1].

題幹中文版:

給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。

你能夠假設每種輸入只會對應一個答案。可是,你不能重複利用這個數組中一樣的元素。

 

目前想到兩種解法:

方法1、暴力查詢,兩邊for循環數組,計算是否存在等於目標值的,存在就返回對應的座標,不存在 返回-1,-1

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

            }
        }
        return [-1,-1]
    }
}

 運行時間和所佔內存:

Runtime: 472 ms, faster than 24.78% of Swift online submissions for Two Sum.
Memory Usage: 21 MB, less than 5.12% of Swift online submissions for Two Sum.

複雜度分析:

時間複雜度 O(n^2)。

方法二:利用字典,由於字典或者集合常常使用的緣由是由於查詢的時間複雜度是O(1),緣由是通常字典和集合會要求他們的key都必須遵照Hashable協議

class Solution {
    func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
       guard nums.count > 1 else{
           return [-1,-1]
       }
       var dict:[Int:Int] = [:]
        for i in 0..<nums.count {
            let item = target-nums[i]
            if let found = dict[item]{
                return [found , i]
            }else{
                dict[(nums[i])] = i
            }
        }
        return [-1, -1]
    }
}

 時間和空間複雜度:

Runtime: 48 ms, faster than 46.77% of Swift online submissions for Two Sum.
Memory Usage: 21.1 MB, less than 5.12% of Swift online submissions for Two Sum.

 

複雜度分析:

時間複雜度 O(n)。

能夠看出方法二運行時間變爲方法一的約1/10,空間複雜度區別不大。

關於時間複雜度和空間複雜度的概念,目前尚不是很是清晰(在以後會一步一步改進的)。

 

 167 -- Two Sum II - Input array is sorted

題幹英文版:

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.
  • You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:

Input: numbers = [2,7,11,15], target = 9

Output: [1,2]

Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

題幹中文版:

給定一個已按照升序排列 的有序數組,找到兩個數使得它們相加之和等於目標數。

函數應該返回這兩個下標值 index1 和 index2,其中 index1 必須小於 index2

說明:

  • 返回的下標值(index1 和 index2)不是從零開始的。
  • 你能夠假設每一個輸入只對應惟一的答案,並且你不能夠重複使用相同的元素。

目前想到的實現思路是根據001的兩數之和,可知加入到字典中的數據的索引是從小到大的,所以咱們能夠知道的是字典中已經存在的索引應該是小於後來遍歷到的,

所以其實現以下:

class Solution {
    func twoSum(_ numbers: [Int], _ target: Int) -> [Int] {
     
      guard numbers.count > 1 else{
           return []
       }
        //由於先加到字典中的確定是數組靠前的下標
       var dict:[Int:Int] = [:]
        for i in 0..<numbers.count {
            let item = target-numbers[i]
            if let found = dict[item]{
                return [found + 1,i + 1]
            }else{
                dict[(numbers[i])] = i
            }
        }
        return []
    }  
}

 運行時間和內存

Runtime: 28 ms, faster than 100.00% of Swift online submissions for Two Sum II - Input array is sorted.
Memory Usage: 21.1 MB, less than 5.09% of Swift online submissions for Two Sum II - Input array is sorted.

 

 關於算法的實現目前的思路:

一、先實現,用如今常常使用到的數據結構去實現,複雜什麼也不要緊,最關鍵是實現它

二、考慮耗時,內存消耗

不要忘了安全校驗:諸如判空,特殊處理等。

 

下期code

Reverse Integer

 

 

有緣看到的親們:文中如有不對之處,還請勞駕之處,謝謝!

相關文章
相關標籤/搜索