- 題目:兩數之和
- 難度:簡單
- 題目描述:給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。你可以假設每種輸入只會對應一個答案。但是,數組中同一個元素不能使用兩遍。
- 示例:給定 nums = [2, 7, 11, 15], target = 9
因爲 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
C語言解法:
算法總結:暴力遍歷尋找兩個數的和爲目標數,找到存放好返回
時間複雜度:O(n * n)
空間複雜度:O(n)
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
//nums用於保存傳入的數組首地址,
//numsSize是傳入數組的數據個數
//target是2數據的和數,
//returnSize用於保存返回的數組中數據的個數
int *result = (int*)malloc(sizeof(int)* 2);
//動態開闢一塊空間用於存儲兩個int型數據的數組,並用result指向這塊內存
int i, j;
for (i = 0; i < numsSize; i++)
{
for (j = 0; j < numsSize; j++){
if (i != j){
if (nums[i] + nums[j] == target){
//如果符合兩個數之和等於目標數據
result[0] = i; //則存入開闢的空間之中
result[1] = j;
*returnSize = 2;
return result;
}
else{
continue;
}
}
}
}
return result;
//程序如果走到這裏,說明並沒有找到兩個數據之和爲target,
//則返回的這個指針,指向的空間中並無數據
}
Java語言解法:
算法總結:將數組以<Integer,Integer>的鍵值對放入HashMap中,然後遍歷一遍數組,在HashMap中尋找與target - nums[i]差值相等的值,如果找到,則說明可以找到兩個值等於target,便將找到的兩個值得下標放入一個數組之中作爲函數返回值返回
時間複雜度:O(n * n)
空間複雜度:O( n )
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> m = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
m.put(nums[i],i); //將數組以鍵值對方式放入HashMap中
if (m.get(target - nums[i]) != null) {
//如果target - nums[i]在HashMap中找到了相等的值,
// 說明找到了這兩個值,則將這兩個值動態創建成數組返回
return new int[]{m.get(target - nums[i]), i};
}
}
return new int[]{0, 0}; //程序運行到這裏說明找不到這兩個數
}