Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6 Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6 Output: [0,1]
nums=[3,2,4]
MyPYTHON
// acceptedclass Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: #if not(2<=len(nums)<=1e4) or not(-1e9<=target<=1e9): #print("error1") #return result=[] a=False for i in range(len(nums)): for j in range(i+1,len(nums)): if nums[i]+nums[j]==target: result.append(i) result.append(j) a=True break if a: break return result nums=[3,2,4] target=6 a=Solution() print(a.twoSum(nums,target))
My_OOP code
//time limit exceededclass Solution:def twoSum(self, nums: List[int], target: int) -> List[int]:if not(2<=len(nums)<=1e4) or not(-1e9<=target<=1e9):print("error1")returnresult=[]a=Falsefor i in nums:for j in range(len(nums)):if not(-1e9<=nums[j]<=1e9):print("error2")returnif nums.index(i) == j:continueelif i+nums[j]==target:result.append(nums.index(i))result.append(j)a=Truebreakif a:breakreturn resultnums=[3,2,4]target=9a=Solution()a.twoSum(nums,target)
Leet_OOP code(1)class Solution:def twoSum(self, nums: List[int], target: int) -> List[int]:hashmap = {}for i in range(len(nums)):hashmap[nums[i]] = ifor i in range(len(nums)):complement = target - nums[i]if complement in hashmap and hashmap[complement] != i:return [i, hashmap[complement]](2)class Solution:def twoSum(self, nums: List[int], target: int) -> List[int]:hashmap = {}for i in range(len(nums)):complement = target - nums[i]if complement in hashmap:return [i, hashmap[complement]]hashmap[nums[i]] = iMy C++ CODE
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int>result; // or vector<int>result(2); int size= nums.size(); for (int i = 0;i<size - 1;i++) { for (int j = i+1;j<size;j++) { if (nums[i]+nums[j]==target) { result.push_back(i); // or result[0]=i;result.push_back(j); // or result[1]=j;} } } return result; } };return result;
Comments
Post a Comment