每日一例 | 一個算法題:兩數(shù)之和

題目來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/two-sum
題目描述
給定一個整數(shù)數(shù)組 nums 和一個整數(shù)目標(biāo)值 target,請你在該數(shù)組中找出 和為目標(biāo)值 的那 兩個 整數(shù),并返回它們的數(shù)組下標(biāo)。
你可以假設(shè)每種輸入只會對應(yīng)一個答案。但是,數(shù)組中同一個元素在答案里不能重復(fù)出現(xiàn)。
你可以按任意順序返回答案。
示例 1:
輸入:
nums = [2,7,11,15],target = 9輸出:[0,1]解釋:因為nums[0] + nums[1] == 9,返回[0, 1]。示例 2:
輸入:
nums = [3,2,4], target = 6輸出:[1,2]示例 3:
輸入:
nums = [3,3], target = 6輸出:[0,1]
提示:
2 <= nums.length <= 103-109 <= nums[i] <= 109-109 <= target <= 109只會存在一個有效答案
提交記錄
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i=0; i < nums.length; i++) {
for (int j = i + 1 ; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[]{i, j};
}
}
}
return new int[] {};
}
}
各位小伙伴可以在思考下,有沒有其他解法,算法題一般都需要考慮性能,兼顧時間和內(nèi)存,請勿忽略這兩個重要參數(shù)哦!

項目路徑:
https://github.com/Syske/example-everyday
本項目會每日更新,讓我們一起學(xué)習(xí),一起進步,遇見更好的自己,加油呀
評論
圖片
表情
