Write your own Leetcode |. 1 and two numbers

Given an integer array nums and a target value target, and ask you to identify the target value of the two integers in the array, and return to their array subscript.

 

You can assume that each input corresponds to only one answer. However, you can not re-use the same array element.

 

Example:

 

Given nums = [2, 7, 11, 15], target = 9

 

Because nums [0] + nums [1] = 2 + 7 = 9

Is returned [0, 1]

 

Source: stay button (LeetCode)

Link: https: //leetcode-cn.com/problems/two-sum

 

C Lv Code:

class Solution {public:vector<int> twoSum(vector<int>& nums, int target) {int i=0;int j=0;vector<int> a;for(;j<nums.size()-1;j++)        {int h=j+1;            i=target-nums[j];for(;h<nums.size();h++)            {if(h==j)                {continue;                }if(nums[h]==i)                {                    a.push_back(j);                    a.push_back(h);return a;                }              }        }return a;    }};

 

py Code:

class Solution(object):def twoSum(self, nums, target):"""        :type nums: List[int]        :type target: int        :rtype: List[int]        """        hashmap = {}for index, num in enumerate(nums):            another_num = target - numif another_num in hashmap:return [hashmap[another_num], index]            hashmap[num] = indexreturn None

 

Published 11 original articles · won praise 2 · Views 852

Guess you like

Origin blog.csdn.net/chengduxiu/article/details/104346768