LeetCode算法笔记
1. 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的值,存在的话返回两个值在数组中的下标。
解题思路:
- 循环遍历
- hash
循环遍历
循环嵌套,复杂度为O(n*n)
hash
遍历一遍数组,存到map中,再遍历一遍找到符合的值。复杂度O(n)
循环遍历代码实现:(swift实现)
1 | /// - Parameters: |
hash代码实现:
1 | //todo |