0%

LeetCode算法

LeetCode算法笔记

1. Two Sum

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.

Example:

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

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

return [0, 1].

题目意思:

给一个Int数组nums,一个Int值target,查找数组中是否存在两个元素相加等于target的值,存在的话返回两个值在数组中的下标。

解题思路:

  1. 循环遍历
  2. hash

循环遍历
循环嵌套,复杂度为O(n*n)

hash
遍历一遍数组,存到map中,再遍历一遍找到符合的值。复杂度O(n)

循环遍历代码实现:(swift实现)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/// - Parameters:
/// - nums: 输入的Int数组
/// - target: 相加得到的值
/// - Returns: 返回结果为[Int]
func TwoSum(_ nums: [Int], _ target: Int) -> [Int] {
for i in 0 ..< nums.count {
for j in i+1 ..< nums.count{
if nums[j] == target - nums[i]{
let result = [i,j]
print(result)
return result
}
}
}
return []
}

hash代码实现:

1
//todo