2021-08-15

Code 1

Question

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Example 1

Input: nums = [1,2,3,1]
Output: true

Example 2

Input: nums = [1,2,3,4]
Output: false

Example 3

Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true

Answer

自己的解法

使用了最直接的方法二层嵌套,测试结果超时。

标准解法

class Solution(object):
    def containsDuplicate(self, nums):
        nums=sorted(nums)
        for i in range(0,len(nums)-1) :
            if nums[i]==nums[i+1] :
                return True
        return False 

先使用内置函数sorted对列表进行排序,然后检验其相邻的两两元素是否相同。

Code 2

Question

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

A subarray is a contiguous part of an array.

Example 1

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6

Example 2

Input: nums = [1]
Output: 1

Example 3

Input: nums = [5,4,-1,7,8]
Output: 23

Answer

方法一

class Solution(object):
    def maxSubArray(self, nums):
        max=nums[0]
        for i in range(1,len(nums)-1) :
            if nums[i-1]>0 :
                nums[i]+=nums[i-1]
                if nums[i]>max :
                    max=nums[i]
        return max
  • 从第二个数开始,如果后一个数大于零,这个数就+=后一个数
  • 最后输出这个数组中最大的数

方法二 : 贪心算法

class Solution(object):
    def maxSubArray(self, nums):
        maxSum=sum=nums[0]
        for i in range(1,len(nums)) :
          sum=max(nums[i],sum+nums[i])
          maxSum=max(sum,maxSum)
        return maxSum
  • 若当前指针所指元素之前的和小于零(就是加上这个数后的和还没有这个数大),则丢弃当前的数列

Code 3

Qusetion

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]
Output: 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]

Solution

自己的解法

class Solution(object):
    def twoSum(self, nums, target):
        l=[]
        flag=1
        for x in range (0,len(nums)) :
            for i in range (0,len(nums)) :
                if i!=x :
                    if nums[i] + nums[x]==target :
                        l.append(nums[i])
                        l.append(nums[x])
                        flag=0
                        break
            if flag==0 :
                break

        return l

标准答案

方法一

思路是找到num2=target-num1,判断是否也在list中。

使用以下两个方法

  • num2 in nums,返回True,表示找到了。
  • nums.index(num2),返回num2对应的索引。
def twoSum(nums, target):
    lens = len(nums)
    j=-1
    for i in range(lens):
        if (target - nums[i]) in nums: #找到可能的num2
            if (nums.count(target - nums[i]) == 1)&(target - nums[i] == nums[i]):
                #nums2出现了一次 & num1=num2
                #如果num2=num1,且nums中只出现了一次,说明找到的是num1本身。
                continue #跳过
            else:
                j = nums.index(target - nums[i],i+1) 
                #index(x,i+1)是从num1后的序列后找num2  
                #避免重复的方法
                break
    if j>0:
        return [i,j]
    else:
        return []

方法二

优化方法一的解法,num2每次从num1之前找。

def twoSum(nums, target):
    lens = len(nums)
    j=-1
    for i in range(1,lens):
        temp = nums[:i]
        if (target - nums[i]) in temp:
            j = temp.index(target - nums[i])
            break
    if j>=0:
        return [j,i]
方法三

用字典模拟哈希求解

def twoSum(nums, target):
    hashmap={
    
    }
    for ind,num in enumerate(nums):
        hashmap[num] = ind
    for i,num in enumerate(nums):
        j = hashmap.get(target - num)
        if j is not None and i!=j:
            return [i,j]
方法四

类似方法二,优化方法三。

def twoSum(nums, target):
    hashmap={
    
    }
    for i,num in enumerate(nums):
        if hashmap.get(target - num) is not None:
            return [i,hashmap.get(target - num)]
        hashmap[num] = i #这句不能放在if语句之前,解决list中有重复值或target-num=num的情况

Code 4

Question

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

Example 1

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.

Example 2

Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Explanation: The arrays we are merging are [1] and [].
The result of the merge is [1].

Example 3

Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
Explanation: The arrays we are merging are [] and [1].
The result of the merge is [1].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.

Answer

自己的答案

class Solution(object):
    def merge(self, nums1, m, nums2, n):
        for i in range(m,m+n) :
            nums1[i]=nums2[i-m]
        for i in range(0,m+n) :
            for j in range(0,m+n-i-1) :
                if nums1[j]>nums1[j+1] :
                    temp=nums1[j]
                    nums1[j]=nums1[j+1]
                    nums1[j+1]=temp
        nums1=nums1[::-1]

先把nums2并到nums1后面,然后再使用排序。

标准答案

双指针

class Solution(object):
    def merge(self, nums1, m, nums2, n):
        sorted=[]
        p1,p2=0,0
        while p1<m or p2<n :
            if p1==m :
                sorted.append(nums2[p2])
                p2+=1
            elif p2==n :
                sorted.append(nums1[p1])
                p1+=1
            elif nums1[p1]<nums2[p2] :
                sorted.append(nums1[p1])
                p1+=1
            else :
                sorted.append(nums2[p2])
                p2+=1
        nums1[:]=sorted

这一方法将两个数组看作队列,每次从两个数组头部取出比较小的数字放到结果中。

Code 5

Question

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

Example 1

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Explanation: [9,4] is also accepted.

Answer

自己的答案

class Solution(object):
    def intersect(self, nums1, nums2):
       m=len(nums1)
       n=len(nums2)
       nums1=sorted(nums1)
       nums2=sorted(nums2)
       inter=[]
       p1=0
       p2=0
       while p1 <m and p2<n :
           if nums1[p1]==nums2[p2] :
               inter.append(nums1[p1])
               p1+=1
               p2+=1
           elif nums1[p1]<nums2[p2] :
               p1+=1
           else :
               p2+=1
       return inter

双指针法,先把两个列表进行排序,然后用两个指针分别控制两个列表,向inter里插入

标准答案

哈希表

class Solution(object):
    def intersect(self, nums1, nums2):
       if len(nums1)> len(nums2) :
           return self.intersect(nums2,nums1)

       m=collections.Counter()

       for num in  nums1 :
           m[num]+=1

       inter=list()
       for num in nums2 :
           if m.get(num,0) >0 :
               inter.append(num)
               m[num]-=1
               if m[num]==0 :
                   m.pop(num)
       return inter

由于同一个数字在两个数组中都可能出现多次,因此需要用哈希表存储每个数字出现的次数。对于一个数字,其在交集中出现的次数等于该数字在两个数组中出现次数的最小值。

  • 首先遍历第一个数组,并在哈希表中记录第一个数组中的每个数字以及对应出现的次数,然后遍历第二个数组,对于第二个数组中的每个数字,如果在哈希表中存在这个数字,则将该数字添加到答案,并减少哈希表中该数字出现的次数。
  • 为了降低空间复杂度,首先遍历较短的数组并在哈希表中记录每个数字以及对应出现的次数,然后遍历较长的数组得到交集

猜你喜欢

转载自blog.csdn.net/yxyxxxyyyy/article/details/119717755