Leet Code OJ 1. Two Sum [Difficulty: Easy]

来源:互联网 发布:风机 scada 数据分析 编辑:程序博客网 时间:2024/05/16 03:07

Leet Code OJ 1. Two Sum [Difficulty: Easy]

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.

Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

翻译:
给定一个整形数组和一个整数target,返回2个元素的下标,它们满足相加的和为target。
你可以假定每个输入,都会恰好有一个满足条件的返回结果。

思路分析:
让所有元素两两想加,把满足条件的输出

MyCode

    #include <stdio.h>    #include <stdlib.h>    #include <string>    int main()    {        int nums[] = { 2, 7, 11, 15, 21 };        static int target = 9;        int a = 0, b = 0;        int num = sizeof(nums) / sizeof(nums[0]);        for (int i = 0; i < num - 1; i++)        {            for (int j = i + 1; j < num ; j++)            {                int result = nums[i] + nums[j];                if (result == target)                 printf("%d + %d = %d \nThe results is [%d , %d]\n", nums[i], nums[j] , result , i , j);            }        }        system("pause");        return 0;    }

其实可以定义一个Vector用来存储符合条件的值,最后输出。
收集其他大神的解法如下,以供学习参考

C++ 解法1

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        unordered_map<int, int> m;        vector<int> res;        for (int i = 0; i < nums.size(); ++i) {            m[nums[i]] = i;        }        for (int i = 0; i < nums.size(); ++i) {            int t = target - nums[i];            if (m.count(t) && m[t] != i) {                res.push_back(i);                res.push_back(m[t]);                break;            }        }        return res;    }};

C++ 解法2

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        unordered_map<int, int> m;        for (int i = 0; i < nums.size(); ++i) {            if (m.count(target - nums[i])) {                return {i, m[target - nums[i]]};            }            m[nums[i]] = i;        }        return {};    }};
1 0