Two Sum:node
Given an array of integers, find two numbers such that they add up to a specific target number.git
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. Please note that your returned answers (both index1 and index2) are not zero-based.算法
You may assume that each input would have exactly one solution.數組
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2less
若是採用暴力搜索的話,是O(n^2)的世界複雜度。能夠考慮把目標數字和現有集合S中的數字想減,獲得一個輔助數組A。而後依次取取A中的元素,從現有幾何S中找相同元素,若是有,則返回此數字的index。 固然,這種方法的複雜度依然是O(n^2). 此時咱們能夠考慮先使用排序算法(快排等)把集合S中的數字進行排序(注意要保存數字的下標)。對於排好序的數組,咱們就能夠使用各類查找算法來加速了。指針
上面是個人初步想法,後來發現能夠經過構建哈希表,使得查找速度變爲O(e)。不過哈希表對空間的消費比較大。排序
Add Two Numbers:ci
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.get
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8input
此題主要是要考慮到指針操做,以及兩數相加的各類狀況。算法的東西沒有考到。