1. 程式人生 > >Leetcode1:兩數之和

Leetcode1:兩數之和

給定一個整數陣列和一個目標值,找出陣列中和為目標值的兩個數。

你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。

示例:

給定 nums = [2, 7, 11, 15], target = 9

因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

C

#include<stdio.h>
#include<malloc.h>

int* twoSum(int* nums, int numsSize, int target);

int main()
{
    int nums[4] = {271115
}; int target = 9; int numsSize = 4; int *index = twoSum(nums, numsSize, target); free(index); } int* twoSum(int* nums, int numsSize, int target) { int i, j; int *array; array = (int*)malloc(sizeof(int) * 2); for (i = 0; i < numsSize; i++) { for (j = i+1
; j < numsSize; j++) { if (nums[i] + nums[j] == target) { array[0] = i; array[1] = j; return array; } } } return array; }

scala

object Solution {
   def twoSum(nums:Array[Int], target: Int)
:
Array[Int] = { var res = new Array[Int](2) for(i <- 0 to nums.length - 1){ for (j <- i + 1 to nums.length - 1){ if (nums(i) + nums(j) == target){ res(0) = i res(1) = j } } } res } }