日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Leetcode刷题实战(1):Two Sum

發布時間:2023/12/10 编程问答 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leetcode刷题实战(1):Two Sum 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Leetcode不需要過多介紹了,今天一邊開始刷題一邊開始總結:

官網鏈接如下:https://leetcode.com/problemset/all/

題1描述:

1Two Sum38.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; }

遞交結果:

復雜度分析:

時間復雜度:O(n^2),空間復雜度O(1).

?

解法2:

為了改善運行時間的復雜度,我們需要一種更有效的方法來檢查數組中是否存在相對應的數。 如果存在,我們需要查找其索引。 維護數組中每個元素到其索引的映射的最佳方法是什么? 哈希表。

我們通過交換空間來減少從O(n)到O(1)的查找時間。 哈希表就是為此目的而構建的,它支持在接近恒定的時間內快速查找。 我說“接近”,因為如果發生碰撞,查找可能會退化為O(n)時間。 但是只要仔細選擇哈希函數,查找哈希表就應該分攤O(1)時間。

一個簡單的實現使用兩次迭代。 在第一次迭代中,我們將每個元素的值及其索引添加到表中。 然后,在第二次迭代中,我們檢查表中是否存在每個元素的補碼(target-nums )。 請注意,補充不能是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"); } }

遞交結果:

復雜度分析:

時間復雜度:O(n),空間復雜度O(n).

總結

以上是生活随笔為你收集整理的Leetcode刷题实战(1):Two Sum的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。