leetcode练习

问题描述

给定一个整数数组,返回两个数字的索引,使它们相加到特定目标。

您可以假设每个输入只有一个解决方案,并且您可能不会两次使用相同的元素。

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:

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

C++代码如下

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) 
 4     {
 5         vector<int> vi;
 6         int size = nums.size();
 7         for(int i=0;i<size;i++)
 8         {
 9             for(int j=i+1;j<size;j++)
10             {
11                 if(nums[i]+nums[j] == target)
12                 {
13                     vi.push_back(i);
14                     vi.push_back(j);
15                     return vi;
16                 }
17             }
18         }
19         return vi;
20     }
21 };
class Solution {
public:
   vector<int> twoSum(vector<int>& nums, int target)
    {
        unordered_map<int, int> m;
        vector<int> vi;
        for (int i=0;i<nums.size();i++)
        {
            m[nums[i]] = i;
        }
        for (int i=0;i<nums.size();i++)
        {
            int other_number = target - nums[i];
            if (m.count(other_number) && m[other_number]!=i)
            {
                vi.push_back(i);
                vi.push_back(m[other_number]);
                break;
            }
        }
        return vi;
    }
};
class Solution {
public:
   vector<int> twoSum(vector<int>& nums, int target)
    {
        unordered_map<int, int> numer_to_id;
        for (int i=0;i<nums.size();i++)
        {
            if (numer_to_id.count(target-nums[i]))
            {
                return{ i,numer_to_id[target - nums[i]] };
            }
            numer_to_id[nums[i]] = i;
        }
        return{};
    }
};

python代码如下:

 1 class Solution(object):
 2     def twoSum(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: List[int]
 7         """
 8         size = len(nums)
 9         i = 0
10         for i in range(size):
11             for j in range(i+1,size):
12                 if nums[i]+nums[j] == target:
13                     return [i,j]

注:

range函数用法:

range(start, stop[, step])
  • start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
  • stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
  • step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
原文地址:https://www.cnblogs.com/LuckCoder/p/10252498.html