LeetCode 【1】 Two Sum --001

5月箴言

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.

Example:

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

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

return [0, 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.

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.


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:

• 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）不是从零开始的。
• 你可以假设每个输入只对应唯一的答案，而且你不可以重复使用相同的元素。

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.


关于算法的实现目前的思路：

1、先实现，用现在经常使用到的数据结构去实现，复杂什么也没关系，最关键是实现它

2、考虑耗时，内存消耗

Reverse Integer

posted on 2019-05-28 17:17 海菲菲菲 阅读(...) 评论(...) 编辑 收藏