LeetCode算法1—— 兩數之和
阿新 • • 發佈:2018-07-20
兩個 -s urn 給定一個整數數組 tar leet div public 返回
給定一個整數數組和一個目標值,找出數組中和為目標值的兩個數。
你可以假設每個輸入只對應一種答案,且同樣的元素不能被重復利用。
示例:
給定 nums = [2, 7, 11, 15], target = 9 因為 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
Solution:
class Solution { public int[] twoSum(int[] nums, int target) { int[] arr = new int[2]; for(int i=1;i<nums.length;i++){for(int j=0;j<i;j++){ if((nums[i] +nums[j])==target){ arr[0] = j; arr[1] = i; break; } } } return arr; } }
LeetCode算法1—— 兩數之和