第十週:1. Two Sum
阿新 • • 發佈:2019-01-24
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].
這道題的思路是兩個迴圈遍歷找相加等於target的數。程式碼如下:
這個程式碼是不能通過的。因為在函式中定義的陣列在函式執行完後已經被系統釋放掉了,會出現以下圖片的錯誤。所以在呼叫函式中得到的結果當然不是計算後的結果。有一個解決辦法就是動態分配記憶體。int* twoSum(int* nums, int numsSize, int target) { int res[2]; int i; for(i=0;i<target;i++) for(int j=i+1;j<target;j++) { if(target==nums[i]+nums[j]) { res[0]=i; res[1]=j; break; } } return res; }
我嘗試下用malloc進行動態分配記憶體到時無補於事,於是我用其他辦法:用java方法就可以搞定了,程式碼如下:
public class Solution { public static int[] twoSum(int[] nums, int target) { int[] result = new int[2]; if (nums == null || nums.length == 0) { return result; } for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { result[0] = i; result[1] = j; return result; } } } return result; } }