1. 程式人生 > >一:Leetcode 第一題

一:Leetcode 第一題

從現在開始刷了,非ACM參賽者,大三,非計算機專業

1、C語言版

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
#include <stdio.h>
#include <stdlib.h>

int* twoSum(int* nums, int numsSize, int target) 
{
    int i,j;
    int *p;
    p=(int *)malloc(sizeof(int) * 2);
    for(i=0;i<numsSize;i++)
       
    {
        for(j=i+1;j<numsSize;j++)
        {
            if(nums[i]+nums[j]==target)
            {
                p[0]=i;
                p[1]=j;
            }
        }
    }
    return p;
}
int main()
{
    int num [4]= {2, 7, 11, 15};
    int tar = 9;
    int* c;
    c=twoSum(num,sizeof(num),tar);
    printf("%d %d",c[0],c[1]);
    return 0;
}

c++版

#include <vector>
#include <iostream>
using namespace std;
class Solution
{
public:
    //void Solution(vector<int>& n, int t){*nums=&n;target=t;}
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        vector<int> out;
        for(int i=0;i<nums.size();i++)
        {
            for(int j=i+1;j<nums.size();j++) 
           {
              if (nums[i]+nums[j]==target)
              {
                  out.push_back(i);
                  out.push_back(j);   
              }      
           }
        }
        return out;
    }
};