剑指offer面试---数组高频系列(建议必会)

目录

1、和为S的两个数字

2、最长不含重复字符的子字符串

3、连续子数组的最大和

4、股票的最大利润

5、最小的k个数

6、 滑动窗口的最大值


1、和为S的两个数字

输入一个数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。

如果有多对数字的和等于s,输出任意一对即可。

你可以认为每组输入中都至少含有一组满足条件的输出。

样例

输入:[1,2,3,4] , sum=7

输出:[3,4]

 

class Solution(object):
    def findNumbersWithSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d=dict()
        for num in nums:
            if num in d.keys():
                return [target-num,num]
            else:
                d[target-num]=num

解析:

字典哈希,妙啊,将每一个数存储在字典中,其中字典的key是target-num,一旦发现已经找到,则直接返回即可

注意初始化字典是d=dict(),进行存储时是d[key]=value的形式


2、最长不含重复字符的子字符串

请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。

假设字符串中只包含从’a’到’z’的字符。

样例

输入:"abcabc"

输出:3
class Solution:
    def longestSubstringWithoutDuplication(self, s):
        """
        :type s: str
        :rtype: int
        """
        
        if not s :
            return 0
        res=0
        d=dict()
        dp=[0]*len(s)
    
        
        for i in range(0,len(s)):
            if s[i] not in d.keys():
                dp[i] = dp[i-1]+1
            else:
                distance = i-d[s[i]]
                if distance > dp[i-1]:
                    dp[i] = dp[i-1]+1
                else:
                    dp[i] = distance
            d[s[i]] = i
            res = max(res,dp[i])
        return res

 

seq = ('Google', 'Runoob', 'Taobao')

dict = dict.fromkeys(seq)

print "新字典为 : %s" % str(dict)

dict = dict.fromkeys(seq, 10)

print "新字典为 : %s" % str(dict)

以上实例输出结果为:

新字典为 : {'Google': None, 'Taobao': None, 'Runoob': None}
新字典为 : {'Google': 10, 'Taobao': 10, 'Runoob': 10}

上述是字典的初始化的一种方式方法,解决最长不重叠子串们可以用动态规划的思路,其中

dp[i]表示的是从0到下标i的最长不重复子串的长度.....,

利用字典d进行s[i]的下标存储,如果前面没有出现过,直接更新dp[i]=dp[i-1]+1,如果出现过,则需需要判断上一次出现到这个字符的距离,根据距离更新dp[i]即可


3、连续子数组的最大和

-------真实被问过,心痛ing....

输入一个 非空 整型数组,数组里的数可能为正,也可能为负。

数组中一个或连续的多个整数组成一个子数组。

求所有子数组的和的最大值。

要求时间复杂度为O(n)。

样例

输入:[1, -2, 3, 10, -4, 7, 2, -5]

输出:18
class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        s=0;res = float('-inf')
        for num in nums:
            if s<=0:s=0
            s+=num
            res=max(res,s)
        return res

变量动态维护输出即可,维护是,最终输出res,res在max(res,s)中不断更新


4、股票的最大利润

假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖 一次 该股票可能获得的利润是多少?

例如一只股票在某些时间节点的价格为[9, 11, 8, 5, 7, 12, 16, 14]。

如果我们能在价格为5的时候买入并在价格为16时卖出,则能收获最大的利润11。

样例

输入:[9, 11, 8, 5, 7, 12, 16, 14]

输出:11
class Solution(object):
    def maxDiff(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        res=0;minv=float("inf")
        
        for num in nums:
            minv = min(minv,num)
            res = max(res,num-minv)
        return res

5、最小的k个数

输入n个整数,找出其中最小的k个数。

注意:

  • 数据保证k一定小于等于输入数组的长度;
  • 输出数组内元素请按从小到大顺序排序;

样例

输入:[1,2,3,4,5,6,7,8] , k=4

输出:[1,2,3,4]
import heapq
class Solution(object):
    def getLeastNumbers_Solution(self, arr, k):
        """
        :type input: list[int]
        :type k: int
        :rtype: list[int]
        """
        if k>len(arr) or k==0:
            return []
        heap=[]
        for i in arr[:k]:
            heapq.heappush(heap,-i)
        for i in arr[k:]:
            if i <-heap[0]:
                heapq.heappop(heap)
                heapq.heappush(heap,-i)
        res = []
        for i in range(k):
            res.append(-heapq.heappop(heap))
        return res[::-1]

'''
heapq 模块的使用。 函数 heapq.heappush() 和 heapq.heappop() 分别在队列 _queue 上插入和删除第一个元素, 并且队列 _queue 保证第一个元素拥有最高优先级


'''

6、 滑动窗口的最大值

给定一个数组和滑动窗口的大小,请找出所有滑动窗口里的最大值。

例如,如果输入数组[2, 3, 4, 2, 6, 2, 5, 1]及滑动窗口的大小3,那么一共存在6个滑动窗口,它们的最大值分别为[4, 4, 6, 6, 6, 5]。

注意:

  • 数据保证k大于0,且k小于等于数组长度。

样例

输入:[2, 3, 4, 2, 6, 2, 5, 1] , k=3

输出: [4, 4, 6, 6, 6, 5]
from collections import deque
class Solution(object):
    def maxInWindows(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        
        if not nums:
            return []
        res=[]
        q=deque([])
        for i in range (len(nums)):
            if i<k-1:
                while q and q[-1]<nums[i]:
                    q.pop()
                q.append(nums[i])
            else:
                while q and q[-1]<nums[i]:
                    q.pop()
                q.append(nums[i])
                
                res.append(q[0]) 
                 
                if q and nums[i-k+1]==q[0]:
                    q.popleft()        
               
        return res

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值