经典算法面试题系列(一)——tow sum
2017-06-09 16:43
288 查看
这道面试题是前段时间,楼主去链家的面试题,印象特别深刻。题目链接https://leetcode.com/problems/two-sum/#/description。惨痛教训告诉我们,刷题是多么的重要。
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:
看了看大神们的各种答案,自己捣鼓了一个自己的。
1.golang版
2.php版
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].中文翻译大概是这样的,有一个整数数组,给定一个数,需要找到相加等于这个数的两个数组下标。楼主当时不知道怎么想的,是不是可以使用二分查找呢?时间复杂度怎么着也得O(logn)。但是看了看各位大神答案,方知自己无知。大神们普遍使用一个hashMap就解决,时间复杂度O(n)。二分查找需要对这个数组进行排序,O(logn)好像也不是很高。
看了看大神们的各种答案,自己捣鼓了一个自己的。
1.golang版
package main import "fmt" func main() { var nums = []int{2, 7, 11, 15} r := towSum(nums, 18) fmt.Println(r) } func towSum(nums []int, target int) []int { n := len(nums) if n <= 1 { return []int{0, 0} } numMap := make(map[int]int) var r []int for i := 0; i < n; i++ { key := target - nums[i] _, ok := numMap[key] if ok { r = append(r, numMap[key], i) } else { numMap[nums[i]] = i } } return r }
2.php版
function twoSum($nums, $target) { $n = count($nums); if($n <= 1) { return [0, 0]; } $mapNum = []; for ($i = 0;$i < $n;$i ++) { $key = $target - $nums[$i]; if (isset($mapNum[$key])) { return [$mapNum[$key], $i]; } else { $mapNum[$nums[$i]] = $i; } } return []; } $nums = [2, 7, 11, 15]; $b = twoSum($nums, 26); var_dump($b);
相关文章推荐
- 白话经典算法系列之十 一道有趣的GOOGLE面试题
- 【白话经典算法系列之十一】一道有趣的GOOGLE面试题 --【解法2】 .
- 白话经典算法系列之十一 一道有趣的GOOGLE面试题 --【解法2】
- 经典算法面试题系列 (二)——three sum
- 【白话经典算法系列之十一】一道有趣的GOOGLE面试题 --【解法2】
- 【白话经典算法系列之十二】数组中只出现1次的两个数字(百度面试题)
- 白话经典算法系列之十二 数组中只出现1次的两个数字(百度面试题)
- 白话经典算法系列之十 一道有趣的GOOGLE面试题
- 白话经典算法系列之十 一道有趣的GOOGLE面试题
- 白话经典算法系列之十 一道有趣的GOOGLE面试题
- 【白话经典算法系列之十二】数组中只出现1次的两个数字(百度面试题)
- 【BAT经典算法面试题系列】求和为n的连续正整数
- 经典基础算法之面试题(系列一)
- 白话经典算法系列之十 一道有趣的GOOGLE面试题 .
- 【白话经典算法系列之十二】数组中只出现1次的两个数字(百度面试题)
- 经典算法研究系列:三、动态规划算法解微软一道面试题[第56题]
- 白话经典算法系列之十 一道有趣的GOOGLE面试题
- 【BAT经典算法面试题系列】求和为n的连续正整数
- 白话经典算法系列之十 一道有趣的GOOGLE面试题
- 【白话经典算法系列之十一】一道有趣的GOOGLE面试题 --【解法2】