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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

1. Leetcode 1. 两数之和 (数组-双向双指针)

發(fā)布時間:2025/4/5 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 1. Leetcode 1. 两数之和 (数组-双向双指针) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個整數數組 nums?和一個整數目標值 target,請你在該數組中找出 和為目標值 target? 的那?兩個?整數,并返回它們的數組下標。你可以假設每種輸入只會對應一個答案。但是,數組中同一個元素在答案里不能重復出現。你可以按任意順序返回答案。示例 1:輸入:nums = [2,7,11,15], target = 9 輸出:[0,1] 解釋:因為 nums[0] + nums[1] == 9 ,返回 [0, 1] 。class Solution:def twoSum(self, nums: List[int], target: int) -> List[int]:array = nums.copy()nums.sort()i, j = 0, len(nums) - 1while i < j:s = nums[i] + nums[j]if s < target:i += 1elif s > target:j -= 1else:breakres = []for k in range(len(nums)):if array[k] == nums[i] or array[k] == nums[j]:res.append(k)return res

魔改: 返回nums中能夠湊出target的兩個值

class Solution:def twoSum(self, nums: List[int], target: int) -> List[int]:nums.sort()i, j = 0, len(nums) - 1while i < j:s = nums[i] + nums[j]if s < target:i += 1elif s > target:j -= 1else:return [nums[i], nums[j]]

魔改:

nums 中可能有多對兒元素之和都等于 target,請你的算法返回, 所有和為 target 的元素對兒,其中不能出現重復, 比如說輸入為 nums = [1,3,1,2,2,3], target = 4,那么算法返回的結果就是: [[1,3],[2,2]]. 時間復雜度-O(NlogN)

class Solution:def twoSum(self, nums: List[int], target: int) -> List[int]:nums.sort()res = []i, j = 0, len(nums) - 1left = nums[i]right = nums[j]while i < j:s = nums[i] + nums[j]if s < target:i += 1elif s > target:j -= 1else s == target:res.append([nums[i], nums[j]])while i < j and nums[i] == left:i += 1while i < j and nums[j] == right:j -= 1return res

總結

以上是生活随笔為你收集整理的1. Leetcode 1. 两数之和 (数组-双向双指针)的全部內容,希望文章能夠幫你解決所遇到的問題。

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