Leetcode刷题实战(1):Two Sum
Leetcode不需要過多介紹了,今天一邊開始刷題一邊開始總結(jié):
官網(wǎng)鏈接如下:https://leetcode.com/problemset/all/
題1描述:
| 1 | Two Sum | 38.80% | Easy |
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].C語言解法一:
/*** Note: The returned array must be malloced, assume caller calls free().*/ int* twoSum(int* nums, int numsSize, int target) {int i, j;int *p = (int *)malloc(2*sizeof(int));for(i=0; i<numsSize-1; i++){for(j=i+1; j<numsSize; j++){if( (*(nums+i) + (*(nums+j))) == target){p[0] = i;p[1] = j; }}} return p; }遞交結(jié)果:
復(fù)雜度分析:
時(shí)間復(fù)雜度:O(n^2),空間復(fù)雜度O(1).
?
解法2:
為了改善運(yùn)行時(shí)間的復(fù)雜度,我們需要一種更有效的方法來檢查數(shù)組中是否存在相對應(yīng)的數(shù)。 如果存在,我們需要查找其索引。 維護(hù)數(shù)組中每個(gè)元素到其索引的映射的最佳方法是什么? 哈希表。
我們通過交換空間來減少從O(n)到O(1)的查找時(shí)間。 哈希表就是為此目的而構(gòu)建的,它支持在接近恒定的時(shí)間內(nèi)快速查找。 我說“接近”,因?yàn)槿绻l(fā)生碰撞,查找可能會退化為O(n)時(shí)間。 但是只要仔細(xì)選擇哈希函數(shù),查找哈希表就應(yīng)該分?jǐn)侽(1)時(shí)間。
一個(gè)簡單的實(shí)現(xiàn)使用兩次迭代。 在第一次迭代中,我們將每個(gè)元素的值及其索引添加到表中。 然后,在第二次迭代中,我們檢查表中是否存在每個(gè)元素的補(bǔ)碼(target-nums )。 請注意,補(bǔ)充不能是nums [i]本身!
class Solution {public int[] twoSum(int[] nums, int target) {Map<Integer, Integer> map = new HashMap<>();for (int i = 0; i < nums.length; i++) {int complement = target - nums[i];if (map.containsKey(complement)) {return new int[] { map.get(complement), i };}map.put(nums[i], i);}throw new IllegalArgumentException("No two sum solution"); } }遞交結(jié)果:
復(fù)雜度分析:
時(shí)間復(fù)雜度:O(n),空間復(fù)雜度O(n).
總結(jié)
以上是生活随笔為你收集整理的Leetcode刷题实战(1):Two Sum的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 详解停车位检测算法 Vision-Bas
- 下一篇: 央行放大招,个人房贷占比受限后,另一条贷