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.
1 2 3 4 5 6
classSolution: deftwo_sum(self, nums, target): for i inrange(len(nums)): for j inrange(i+1, len(nums)): if nums[j] == target - nums[i]: return [i, j]
(2)Add Two Numbers
(4)Median of Two Sorted Arrays
(26) Remove Element from Sorted Array
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once.(巨大前提是数据广义单增) The relative order of the elements should be kept the same. Then return the number of unique elements in nums.
Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:
Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums. Return k.
1 2 3 4 5 6 7 8
classSolution(object): defremoveDuplicates(self, nums): dummy=1 for i inrange(1,len(nums)): if nums[i]!=nums[i-1]: nums[dummy]=nums[i] dummy+=1 return dummy
(27) Remove Elements
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution(object): defremoveElement(self, nums, val): index=0 for i inrange(len(nums)): if nums[i]!=val: nums[index]=nums[i] index+=1 return index
classSolution(object): defsearchInsert(self, nums, target): left=0 right=len(nums)-1 while left<=right: mid=(left+right)//2 if nums[mid]==target: return mid elif nums[mid]>target: right=mid-1 else: left=mid+1 return left
Method 2: Traditional Index
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution(object): defsearchInsert(self, nums, target): k=0 s=0 for i inrange(len(nums)): if nums[i]!=target: k+=1 else: return k for j inrange(1,len(nums)): if nums[j-1] < target: if nums[j] > target: return j return(len(nums))