1. 设计前中后队列
思路:python代码直接利用list的insert特性
class FrontMiddleBackQueue:def __init__(self):self.queque = []def pushFront(self, val: int) -> None:self.queque.insert(0, val)def pushMiddle(self, val: int) -> None:self.queque.insert(len(self.queque)//2, val)def pushBack(self, val: int) -> None:self.queque.append(val)def popFront(self) -> int:if self.queque: return self.queque.pop(0)return -1def popMiddle(self) -> int:if self.queque: return self.queque.pop((len(self.queque)-1)//2)return -1def popBack(self) -> int:if self.queque: return self.queque.pop(-1)return -1# Your FrontMiddleBackQueue object will be instantiated and called as such:
# obj = FrontMiddleBackQueue()
# obj.pushFront(val)
# obj.pushMiddle(val)
# obj.pushBack(val)
# param_4 = obj.popFront()
# param_5 = obj.popMiddle()
# param_6 = obj.popBack()
c++实现:利用vector特性
class FrontMiddleBackQueue {
public:vector<int> queue;FrontMiddleBackQueue() {}void pushFront(int val) {queue.insert(queue.begin(), val);}void pushMiddle(int val) {int pos = queue.size() / 2;queue.insert(queue.begin() + pos, val);}void pushBack(int val) {queue.push_back(val);}int popFront() {if(queue.empty()){return -1;}int value = queue[0];queue.erase(queue.begin());return value;}int popMiddle() {if(queue.empty()){return -1;}int pos = (queue.size()-1)/2;int value = queue[pos];queue.erase(queue.begin() + pos);return value;}int popBack() {if(queue.empty()){return -1;}int value = queue[queue.size()-1];// queue.erase(queue.end()-1);queue.pop_back();return value;}
};/*** Your FrontMiddleBackQueue object will be instantiated and called as such:* FrontMiddleBackQueue* obj = new FrontMiddleBackQueue();* obj->pushFront(val);* obj->pushMiddle(val);* obj->pushBack(val);* int param_4 = obj->popFront();* int param_5 = obj->popMiddle();* int param_6 = obj->popBack();*/
2. 字典序的第K小数字
思路:
python代码:
class Solution:def getNode(self, n, first, second):nums = 0while first <= n:nums += min(n+1, second) - firstfirst *= 10second *= 10return numsdef findKthNumber(self, n: int, k: int) -> int:cur = 1k -= 1while k > 0:nums = self.getNode(n, cur, cur+1)if nums <= k: #第k个数不在以cur为根节点的树上cur += 1 #cur在字典序数组中从左往右移动k -= numselse:#在子树中cur *= 10 #cur在字典序数组中从上往下移动k -= 1 #刨除根节点return cur
c++实现:
class Solution {
public:int getNode(long n, long first, long second){int nums = 0;while(first <= n){nums += min(n+1, second) - first;first *= 10;second *= 10;}return nums;}int findKthNumber(int n, int k) {long cur = 1;k -= 1;while(k > 0){int nums = getNode(n, cur, cur + 1);if(nums <= k){cur += 1;k -= nums;}else{cur *= 10;k -= 1;}}return cur;}
};
3.复原 IP 地址
思路:递归+回溯
分两种情况:如果开头是0 需要单独拿出来, 不是的话 在分 1位, 2位, 3位的 只是需要注意,两位 三位需要有数字范围限定
class Solution:def backtrace(self, s, track, count):if len(track) == 4 and count == self.length:self.res.append('.'.join(track))returnif len(track) == 4 and count != self.length:returnif count == self.length:returnn = len(s)for i in range(n):if s[i] == '0': #0要单独拿出来 self.backtrace(s[i+1:], track + ['0'], count + 1)else:self.backtrace(s[i+1:], track + [s[i]], count + 1)#一位数的if i < n-1 and 10 <= int(s[i:i+2])<=99:self.backtrace(s[i+2:], track + [s[i:i+2]], count + 2)#两位数的if i < n-2 and 100 <= int(s[i:i+3])<=255:self.backtrace(s[i+3:], track + [s[i:i+3]], count + 3)#三位数的def restoreIpAddresses(self, s: str) -> List[str]:self.res = []self.length = len(s)if self.length > 12:return []self.backtrace(s, [], 0)return self.res
c++实现:
class Solution {
public:vector<string> res;void backtrace(string s, vector<string>& track, int count, int length){if(track.size() == 4 && count == length){ string temp = "";for(int i = 0; i < 4; i++){temp += track[i];if(i != 3){temp += ".";}}res.push_back(temp);return;}if(track.size() == 4 && count != length){return;}if(count == length){return;}int n = s.size();for(int i = 0; i < n; i++){if(s[i] == '0'){track.push_back("0");backtrace(s.substr(i + 1, n - 1), track, count + 1, length);track.pop_back();}else{string temp_;temp_ = s[i];track.push_back(temp_);backtrace(s.substr(i + 1, n - 1), track, count + 1, length);track.pop_back();if(i < n-1 && 10 <= atoi(s.substr(i, 2).c_str()) && atoi(s.substr(i, 2).c_str()) <= 99){track.push_back(s.substr(i, 2));backtrace(s.substr(i + 2, n - 2), track, count + 2, length);track.pop_back();}if(i < n-2 && 100 <= atoi(s.substr(i, 3).c_str()) && atoi(s.substr(i, 3).c_str()) <= 255){track.push_back(s.substr(i, 3));backtrace(s.substr(i + 3, n - 3), track, count + 3, length);track.pop_back();}}}} vector<string> restoreIpAddresses(string s) {int length = s.size();if(length > 12){return {};}vector<string> track;backtrace(s, track, 0, length);return res;}
};
4.无重复字符的最长子串
思路1.暴力破解
"""
给一个字符串,找出最长的没有重复字符的子字符串,并返回该字符串的长度
"""
# class solution:
def lengthOfLongestSubstring(s):max_len=0if(len(s)==1 or len(s)==0):max_len=len(s)#第一层循环从最左侧到右侧第二个,第二层循环从第一层紧跟的一个到最后一个,找出所有不重复的子字符串,比较长度得出最长。for i in range(0,len(s)-1):for j in range(i+1,len(s)):if s[j] in s[i:j]:if j-i>max_len:right=jleft=imax_len=right-leftarray=s[i:j]breakelif j==len(s)-1:if max_len<j-i+1:max_len=j-i+1array = s[:(j+1)]return max_len,array
# # sol=solution()
result,array=lengthOfLongestSubstring('abcabcbbb')
print(result,array)
思路2.滑动窗口
class Solution:def lengthOfLongestSubstring(self, s: str) -> int: dict_={}res = 0left,right=0,0while right<len(s):dict_[s[right]]=dict_.get(s[right],0)+1while dict_[s[right]]>1:dict_[s[left]]-=1left+=1res = max(res, right-left+1)right+=1return res
思路3.利用字典,用key存储字符 value存储其相应的index
#hash 用key存储字符 value存储其相应的index
class Solution:def lengthOfLongestSubstring(self, s):dict_={}max_length = 0start = 0for index,char in enumerate(s):if char in dict_ and start<=dict_[char]:start = dict_[char]+1else:max_length = max(max_length, index - start +1)dict_[char] = indexprint('==dict_:',dict_)return max_length
s = 'abcdafg'
sol = Solution()
res = sol.lengthOfLongestSubstring(s)
print('res:', res)
5,给出两个有序的数字列表,长度分别为m,n。找到这两个列表中的中间值。
"""
给出两个有序的数字列表,长度分别为m,n。找到这两个列表中的中间值。
"""
class solution:def findMedianSortedArrays(self,nums1,nums2):nums3=[0]*(len(nums1)+len(nums2))l_i,r_i,i=0,0,0#两个列表进行比较,将较小值放入新的列表while(l_i<len(nums1)) and (r_i<len(nums2)):if nums1[l_i]<nums2[r_i]:nums3[i]=nums1[l_i]l_i+=1else:nums3[i]=nums2[r_i]r_i+=1i+=1#将未遍历完的列表加入新的列表if l_i!=len(nums1):nums3[i:]=nums1[l_i:]else:nums3[i:]=nums2[r_i:]len_3=len(nums3)if len_3%2!=0:return float(nums3[(len_3-1)//2])return (nums3[len_3//2-1]+nums3[len_3//2])/2
sol=solution()num1=[1,3,5]
num2=[2,4]
result=sol.findMedianSortedArrays(num1,num2)
print(result)
6.将字符串 "PAYPALISHIRING"
以Z字形排列成给定的行数:
P A H N
A P L S I I G
Y I R
之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR"
暴力解法:
class Solution:def convert(self,s,numRows):n=numRowsres_list=[]l=len(s)if n==1:return sfor i in range(n):for j in range(l):if j%(2*n-2)==i or j%(2*n-2)==2*n-2-i:res_list.append(s[j])res=''.join(res_list)return ressol=Solution()
res=sol.convert('abcdefg',3)
print(res)
更好的解法,不需要遍历整个字符串长度
class Solution:def convert(self, s, numRows):str_length=len(s)node_length=2*numRows-2result=''if str_length==0 or numRows==0 or numRows==1:return s#从第一行遍历到最后一行for i in range(numRows):#大的改进for j in range(i,str_length,node_length):#第一行和最后一行和普通行的整列数据result+=s[j]#得到斜着部分 j-2*i+node_lengthif i!=0 and i!=numRows-1 and j-2*i+node_length<str_length:result+=s[j-2*i+node_length]return resultsol=Solution()
res=sol.convert('abcdefg',3)
print(res)
7. 丢失的数字
思路:和减去nums中的数,就是缺失的啦
class Solution:def missingNumber(self, nums: List[int]) -> int:n = len(nums)sum_ = n*(n+1)//2for num in nums:sum_ -= numreturn sum_
c++实现:
class Solution {
public:int missingNumber(vector<int>& nums) {int n = nums.size();int sum_ = n*(n+1)/2;for(auto num: nums){sum_ -= num;}return sum_;}
};
8.整数反转
class Solution:def reverse(self, x):""":type x: int:rtype: int"""sign = [-1, 1][x > 0]res=sign*int(str(abs(x))[::-1])return res if -(2**31)<=res<=2**31-1 else 0
sol=Solution()
res=sol.reverse(-123)
print(res)
c++实现:
class Solution {
public:int reverse(int x) {//栈int res = 0;while(x != 0){int temp = x % 10;x /=10;if(res > INT_MAX/10 || (res == INT_MAX/10 && temp > 7)) return 0;if(res < INT_MIN/10 || (res == INT_MIN/10 && temp < -8)) return 0;res = res * 10 + temp;}return res;}};
9.把字符串转换成整数
'
思路:删除首尾空格
判断删除空格后的第一个字符是否是+或者-
如果是+或者- 下一个字符必须是数字 否则返回0,是的话就一直合并到字母
如果是数字就一直合并到出现字母停止
# 删除首尾空格
# 判断删除空格后的第一个字符是否是+或者-# 如果是+或者- 下一个字符必须是数字 否则返回0,是的话就一直合并到字母# 如果是数字就一直合并到出现字母停止
class Solution:def strToInt(self, str):new_str = str.strip()if len(new_str) == 0:return 0sign, start = 1, 0if new_str[0] == "-":sign = -1start = 1if new_str[0] == "+":sign = 1start = 1res = 0for c in new_str[start:]:if "0" <= c <= "9":res = 10 * res + int(c)else:breakres = sign * resif res > 2 ** 31 - 1:return 2 ** 31 - 1elif res < -2 ** 31:return -2 ** 31else:return resstr = "4193 with words"
sol = Solution()
res = sol.strToInt(str)
print(res)
10.外观数列
思路:核心是双指针做聚类,只不过需要聚类的字符串需要更新,外面需要套一个for循环
python代码:
class Solution:def countAndSay(self, n: int) -> str:#双指针外面 套一个循环n就行pre = ""res = "1"for k in range(1, n):pre = resres = ""left, right = 0, 0while right < len(pre):while right < len(pre) and pre[left] == pre[right]:right += 1res += str(right - left) + pre[left]left = rightreturn res
c++代码:
class Solution {
public:string countAndSay(int n) { string res = "1";string s = "";for(int k = 1; k < n; k++){s = res;res = "";int left = 0, right = 0;while(right < s.size()){while(right < s.size() && s[left] == s[right]){right++;}res += to_string(right - left) + s[left];left = right;}}return res;}
};
11.只出现一次的数字 III
思路1:hash
class Solution:def singleNumber(self, nums: List[int]) -> List[int]:dict_ = {}for num in nums:if num not in dict_:dict_[num] = 1else:dict_[num] -= 1res = []for key in dict_:if dict_[key] != 0:res.append(key)return res
c++:
class Solution {
public:vector<int> singleNumber(vector<int>& nums) {map<int, int> dict_;for(auto num: nums){if(dict_.count(num) == 0){dict_[num] += 1;}else{dict_[num] -= 1;}}vector<int> res;map<int, int> ::iterator it;for(it = dict_.begin(); it != dict_.end(); it++){if(it->second != 0){res.push_back(it->first);}}return res;}
};
思路2:因为有两个不同的数,如果能将两个不同的数分组开,那么异或一下自然就出来了。
class Solution {
public:vector<int> singleNumber(vector<int>& nums) {//div保持的是两位要找的数的异或 ^long div = 0;int a = 0, b = 0;for(int num : nums)div ^= num;//取最低位的1,这个1表示的是在这个bit,a与b一个为0一个为1div &= -div;for(int num : nums){ if(div & num)a ^= num;else{b ^= num;}}return {a,b};}
};
12. 整数转罗马数字
思路:贪心算法
class Solution:def intToRoman(self, num: int) -> str:# 使用哈希表,按照从大到小顺序排列dict_ = {1000:'M', 900:'CM', 500:'D', 400:'CD', 100:'C', 90:'XC', 50:'L', 40:'XL', 10:'X', 9:'IX', 5:'V', 4:'IV', 1:'I'}res = ""for key in dict_:count = num // keyif count != 0:res += count*dict_[key]num %= keyreturn res;
c++实现:
class Solution {
public:string intToRoman(int num) {int value[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};string str_[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};string res;for(int i = 0; i < 13; i++){while(num >= value[i]){num -= value[i];res += str_[i];}}return res;}
};
13.罗马数字转整数
思路:贪心算法
class Solution:def romanToInt(self, s: str) -> int:dict_ = {'M':1000,"CM":900,'D':500, "CD":400, 'C':100, "XC":90, 'L':50,"XL":40, 'X':10, "IX":9, 'V':5, "IV":4,'I':1}n = len(s)res = 0i= 0while i < n:if i < n-1 and s[i:i+2] in dict_:res += dict_[s[i:i+2]]i += 2else:res += dict_[s[i]]i += 1return res
c++实现:
class Solution {
public:int romanToInt(string s) {int value[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};string str_[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};map<string, int> dict_;int length = sizeof(value)/sizeof(value[0]);for(int i = 0; i < length; i++){dict_[str_[i]] = value[i];}int res = 0;int i = 0;int n = s.size();while(i < n){if (i < n-1 && dict_.count(s.substr(i, 2))){res += dict_[s.substr(i, 2)];i += 2;}else{res += dict_[s.substr(i, 1)];i++;}}return res;}
};
14. 最长公共前缀
找最短字符串即可
class Solution:def longestCommonPrefix(self, strs: List[str]) -> str:min_length = min([len(str_) for str_ in strs]) #最短字符串for i in range(min_length):for j in range(1, len(strs)):if strs[0][i] != strs[j][i]:return strs[0][:i]return strs[0][:min_length]
c++实现:
class Solution {
public:string longestCommonPrefix(vector<string>& strs) {int min_lenth = INT_MAX;int n = strs.size();for(int i = 0; i < n; i++){int temp_ = strs[i].size();if(temp_ < min_lenth){min_lenth = temp_;}} for(int i = 0; i < min_lenth; i++){for (int j = 1; j < n; j++){if(strs[0][i] != strs[j][i]){return strs[0].substr(0, i);}}}return strs[0].substr(0, min_lenth);}
};
14.三数之和
思路1: 固定两数,寻找第三个数,两层循环,最复杂解法,列表比较大时,时间会很长
class Solution:def threeSum(self, nums):""":type nums: List[int]:rtype: List[List[int]]"""result=[]nums.sort()length=len(nums)for i in range(length-1):for j in range(i+1,length):if -(nums[i]+nums[j]) in nums[j+1:]:tmp=[nums[i],nums[j],-(nums[i]+nums[j])]if tmp not in result:result.append(tmp)return result
思路2: 双指针,固定一个数,让其余两个数从第一个数+1和尾 向中间靠近,只需要循环一遍
# 双指针:排好序以后,双指针去寻找两数之和等于第一个
class Solution:def threeSum(self, nums):nums = sorted(nums)res = []n = len(nums)print('==nums:', nums)for i in range(n):if i>0 and nums[i]==nums[i-1]:#去除相同的第一个数[-1, 0, 1, 2, -1, -4]continuestart = i + 1end = n - 1# print('==start:', start)# print('==end:', end)while start < end:if nums[i] + nums[start] + nums[end] == 0:res.append([nums[i], nums[start], nums[end]])start += 1end -= 1while start<end and nums[start]==nums[start-1]:# 首部出现连续两个数[-2, 0, 0, 2, 2]start+=1while start<end and nums[end]==nums[end+1]:# 尾部出现连续两个数[-2, 0, 0, 2, 2]end-=1elif (nums[i] + nums[start] + nums[end]) > 0:end -= 1else:start += 1print('==res:', res)return res# nums = [-1, 0, 1, 2, -1, -4]
nums = [-2, 0, 0, 2, 2]
sol = Solution()
sol.threeSum(nums)
十五:最接近的三数之和
固定一个数,让其余两个数从首,尾 向中间靠近,只需要循环一遍
class Solution:def threeSumClosest(self, nums, target):""":type nums: List[int]:type target: int:rtype: int"""nums.sort()length=len(nums)res=[]for i,num in enumerate(nums[0:-2]):l,r=i+1,length-1if num+nums[r]+nums[r-1]<target:#从右边遍历res.append(num+nums[r]+nums[r-1])elif num+nums[l]+nums[l+1]>target:#从左边遍历res.append(num + nums[l] + nums[l+1])else:while l<r:#左边索引小于右边时,遍历res.append(num + nums[l] + nums[r])if num+nums[l]+nums[r]<target:l+=1elif num+nums[l]+nums[r]>target:r-=1else:return targetres.sort(key=lambda x:abs(x-target))return res[0]nums = [-1,2,1,-4]
target = 1.
sol=Solution()
result=sol.threeSumClosest(nums,target)
print(result)
16.给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/description/
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
class Solution:def letterCombinations(self, digits):""":type digits: str:rtype: List[str]"""if not digits: return []#建立字典table={'2':['a','b','c'],'3':['d','e','f'],'4':['g','h','i'],'5':['j','k','l'],'6':['m','n','o'],'7':['p','q','r','s'],'8':['t','u','v'],'9':['w','x','y','z']}result=['']for digit in digits:str_list=[]for char_single in table[digit]:str_list+=[x+char_single for x in result]print(str_list)#result存储前一个数对应的字母result=str_listreturn result
17.Pow(x, n)
思路:一层一层递归 超时
class Solution:def myPow(self, x: float, n: int) -> float:if n == 0:return 1if n == 1:return xif n > 0:return x*self.myPow(x, n-1)else:return 1/(x*self.myPow(x, abs(n)-1))
思路:快速幂
class Solution:def help(self, x, n):if n == 0:return 1temp = self.myPow(x, n//2)if n % 2 == 0:return temp*tempelse:return x*(temp*temp)def myPow(self, x: float, n: int) -> float:if n > 0:return self.help(x, n)else:return 1 / self.help(x, -n)
c++实现:
class Solution {
public:double help(double x, long long n){if(n == 0){return 1.;}double temp = help(x, n / 2);if (n % 2){return x*(temp*temp);}else{return temp*temp;}}double myPow(double x, int n) {long long N = n;if(n > 0){return help(x, N);}else{return 1. / help(x, -N);}}
};
18:螺旋矩阵
思路:循环打印
class Solution:def help(self, x1, x2, y1, y2, matrix):for i in range(x1, x2 + 1):self.res.append(matrix[y1][i]) #1, 2, 3for i in range(y1 + 1, y2 + 1):self.res.append(matrix[i][x2]) #6, 9if x1 < x2 and y1 < y2:for i in range(x2 - 1, x1, -1):self.res.append(matrix[y2][i]) #8for i in range(y2, y1, -1):self.res.append(matrix[i][x1]) #7, 4def spiralOrder(self, matrix: List[List[int]]) -> List[int]:self.res = []x1, y1, x2, y2 = 0, 0, len(matrix[0]) - 1, len(matrix) - 1while(x1 <= x2 and y1 <= y2):self.help(x1, x2, y1, y2, matrix)x1 += 1y1 += 1x2 -= 1 y2 -= 1return self.res
c++实现:
class Solution {
public:vector<int> res;void help(int x1, int y1, int x2, int y2, vector<vector<int>>& matrix){for(int i = x1; i < x2 + 1; i++){res.push_back(matrix[y1][i]); //1, 2, 3}for(int i = y1 + 1; i < y2 + 1; i++){res.push_back(matrix[i][x2]); //6, 9}if(x2 > x1 && y2 > y1){for(int i = x2 - 1; i > x1 ; i--){res.push_back(matrix[y2][i]); //8}for(int i = y2; i > y1 ; i--){res.push_back(matrix[i][x1]); //7,4}} }vector<int> spiralOrder(vector<vector<int>>& matrix) {int x1 = 0, y1 = 0, x2 = matrix[0].size() - 1, y2 = matrix.size() - 1;while(x1 <= x2 && y1 <= y2){help(x1, y1, x2, y2, matrix);x1++;y1++;x2--;y2--;}return res;}
};
20-1.用栈实现队列
思路:就是将先进后出换成先进先出,这样的话在出队列的时候,需要将栈A除去栈底的元素给栈B,在弹出A中元素,在把栈B给A,一直循环保持栈A只有一个元素
python代码:
class MyQueue:def __init__(self):"""Initialize your data structure here."""self.stack_A = []self.stack_B = []def push(self, x: int) -> None:"""Push element x to the back of queue."""self.stack_A.append(x)def pop(self) -> int:"""Removes the element from in front of queue and returns that element."""while len(self.stack_A)>1:self.stack_B.append(self.stack_A.pop())value = self.stack_A.pop()while len(self.stack_B):self.stack_A.append(self.stack_B.pop())return valuedef peek(self) -> int:"""Get the front element."""if len(self.stack_A):return self.stack_A[0]else:return Nonedef empty(self) -> bool:"""Returns whether the queue is empty."""if len(self.stack_A):return Falseelse:return True# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
c++:
#include <map>
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
#include <limits.h>
#include <math.h>
#include <stack>class MyQueue {
public:stack<int> stack_A;stack<int> stack_B;/** Initialize your data structure here. */MyQueue() {} /** Push element x to the back of queue. */void push(int x) {stack_A.push(x);} /** Removes the element from in front of queue and returns that element. */int pop() {if(stack_B.empty()){while (!stack_A.empty()){stack_B.push(stack_A.top());stack_A.pop();}} int value = stack_B.top();stack_B.pop();return value;} /** Get the front element. */int peek() {int res = pop();stack_B.push(res);return res;} /** Returns whether the queue is empty. */bool empty() {return stack_A.empty() && stack_B.empty();}
};int main()
{MyQueue* obj = new MyQueue();int x=1;obj->push(x);x=2;obj->push(x);x=3;obj->push(x);int param_2 = obj->pop();cout<<"param_2:"<<param_2<<endl;int param_3 = obj->peek();cout<<param_3<<endl;bool param_4 = obj->empty();cout<<param_4<<endl;delete obj;obj=NULL;return 0;
}
20-2.用队列实现栈
思路:就是将先进先出换成先进后出,这样的话在出栈的时候,需要将队列A除去队尾的元素给队列B,在弹出A中元素,在把队列B给A,一直循环保持队列A只有一个元素
python代码:
class MyStack:def __init__(self):"""Initialize your data structure here."""self.quene_A = []self.quene_B = []def push(self, x):"""Push element x onto stack."""self.quene_A.append(x)def pop(self):"""Removes the element on top of the stack and returns that element."""if len(self.quene_A)==0:return Nonewhile len(self.quene_A)>1:self.quene_B.append(self.quene_A.pop(0))value = self.quene_A.pop()self.quene_A=self.quene_Bself.quene_B =[]return valuedef top(self):"""Get the top element."""if len(self.quene_A) == 0:return Nonereturn self.quene_A[-1]def empty(self):"""Returns whether the stack is empty."""if len(self.quene_A):return Trueelse:return False
# Your MyStack object will be instantiated and called as such:
obj = MyStack()
obj.push(1)
obj.push(2)
obj.push(3)
param_2 = obj.pop()
print('==param_2:', param_2)
param_3 = obj.top()
print('==param_3:', param_3)
param_4 = obj.empty()
print('=param_4:', param_4)
c++:
#include <map>
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
#include <limits.h>
#include <math.h>class MyStack {
public:queue<int> queue_A;queue<int> queue_B;/** Initialize your data structure here. */MyStack() {}/** Push element x onto stack. */void push(int x) {queue_A.push(x);}/** Removes the element on top of the stack and returns that element. */int pop() {int length = queue_A.size();cout<<length<<endl;while (length>1)//让A中只有一个元素{ length--;queue_B.push(queue_A.front());queue_A.pop();}int res = queue_A.front();//弹出的A就是栈顶元素queue_A.pop();queue_A = queue_B;while (!queue_B.empty()){queue_B.pop();}return res;}/** Get the top element. */int top() {return queue_A.back();}/** Returns whether the stack is empty. */bool empty() {return queue_A.empty();}
};int main()
{MyStack* obj = new MyStack();int x=1;obj->push(x);x=2;obj->push(x);x=3;obj->push(x);int param_2 = obj->pop();cout<<"param_2:"<<param_2<<endl;int param_3 = obj->top();cout<<param_3<<endl;bool param_4 = obj->empty();cout<<param_4<<endl;delete obj;obj=NULL;return 0;
}
二十一,实现最大子列和问题
时间复杂度O(N)
class Solution:def maxSubArray(self, nums):for i in range(1,len(nums)):nums[i]+=max(nums[i-1],0)print('==nums:', nums)return max(nums)
sol =Solution()
# nums =[-1]
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
res = sol.maxSubArray(nums)
print('res:',res)
二十二,利用链表实现多项式加法
解题思路
存储方式可以采用链表存储和数组存储,为了熟悉链式操作,所以采用链表存储。其中指针定义的格式如下所示
class Node:def __init__(self, coef, exp):self.coef = coefself.exp = expself.next = Nonedef get_data(self):return [self.coef, self.exp]class List:def __init__(self, head):self.head = head# 添加节点def addNode(self, node):temp = self.headwhile temp.next is not None:temp = temp.nexttemp.next = node# 打印def printLink(self, head):res = []while head is not None:res.append(head.get_data())head = head.nextreturn resdef adds(l1, l2): # l1,l2为链表,且不为空p1 = l1.headp2 = l2.headaddRes = []while (p1 is not None) and (p2 is not None):tmp1_exp = p1.get_data()[1]tmp2_exp = p2.get_data()[1]# 当指数相同时,系数相加if tmp1_exp == tmp2_exp:addRes.append([p1.get_data()[0] + p2.get_data()[0], p1.get_data()[1]])p1 = p1.nextp2 = p2.nextif tmp1_exp > tmp2_exp:addRes.append([p1.get_data()[0], p1.get_data()[1]])p1 = p1.nextif tmp1_exp < tmp2_exp:addRes.append([p2.get_data()[0], p2.get_data()[1]])p2 = p2.nextwhile p1 is not None:addRes.append([p1.get_data()[0], p1.get_data()[1]])p1 = p1.nextwhile p2 is not None:addRes.append([p2.get_data()[0], p2.get_data()[1]])p2 = p2.nextres1 = []for item in addRes:if item[0] != 0:res1.append(item[0])res1.append(item[1])if len(res1) == 0:return [0, 0]return res1def muls(l1, l2):p1 = l1.headp2 = l2.headmulRes = []while p1 is not None:tmp1 = p1.get_data()while p2 is not None:tmp2 = p2.get_data()mulRes.append([tmp1[0] * tmp2[0], tmp1[1] + tmp2[1]])p2 = p2.nextp2 = l2.headp1 = p1.nextexps = []for item in mulRes:if item[1] not in exps:exps.append(item[1])d = {}for item in mulRes:if item[1] not in d.keys():d[item[1]] = 0d[item[1]] += item[0]d = sorted(d.items(), key=lambda x: x[0], reverse=True)res2 = []for item in d:# 如果多项式中出现抵消,即系数为0需要删除if item[1] != 0:res2.append(item[1])res2.append(item[0])# 如果最后出现空数组需要输出0 0if len(res2) == 0:return [0, 0]return res2def print_list(x):for i in x[:-1]:print(i, end=' ')print(x[-1], end='')# 输入
# a1 = list(map(int, input().split()))
# a2 = list(map(int, input().split()))
a1=[4,3,4,-5,2,6,1,-2,0]
a2=[3,5,20,-7,4,3,1]# 变为链表
if a1[0] != 0:head1 = Node(a1[1], a1[2])l1 = List(head1)if a1[0] > 1:for i in range(a1[0] - 1):node = Node(a1[i * 2 + 3], a1[i * 2 + 4])l1.addNode(node)if a2[0] != 0:head2 = Node(a2[1], a2[2])l2 = List(head2)if a2[0] > 1:for i in range(a2[0] - 1):node = Node(a2[i * 2 + 3], a2[i * 2 + 4])l2.addNode(node)
# 考虑链表长度进行运算
if len(a1) == 1 and len(a2) == 1: # 都为0,则输出都为0print_list([0, 0])print()print_list([0, 0])
elif len(a1) == 1 and len(a2) > 1: # 一个为0,另一个为多项式print_list([0, 0])print()print_list(a2[1:])
elif len(a2) == 1 and len(a1) > 1:print_list([0, 0])print()print_list(a1[1:])
else: # 都为多项式# print_list(muls(l1, l2))# print()print_list(adds(l1, l2))
23-1.滑动窗口中位数
#滑动窗口 双指针
class Solution:def medianSlidingWindow(self, nums, k):left, right = 0, 0length = len(nums)res = []while right + k <= length:part_num = sorted(nums[left:right + k])print('==part_num:', part_num)if k % 2 == 1: # 奇数res.append(part_num[k // 2])else:res.append((part_num[k // 2] + part_num[k // 2 - 1]) / 2)left += 1right += 1print(res)return resnums = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
sol = Solution()
sol.medianSlidingWindow(nums, k)
24:一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
1.
class Solution(object):def numWays(self, n):""":type n: int:rtype: int"""if n==0:return 1if 1<=n<3:return ndp = [0]*(n+1)dp[1],dp[2] = 1,2for i in range(3, n+1):dp[i] = dp[i-1]+dp[i-2]return dp[-1]%(1000000007)
2.
class Solution(object):def climbStairs(self, n):""":type n: int:rtype: int"""i=1j=2for _ in range(3,n):i,j=j,i+jreturn i+j if n>2 else n
24-2.使用最小花费爬楼梯
class Solution:def minCostClimbingStairs(self, cost):dp = [0]*len(cost)dp[0],dp[1] =cost[0],cost[1]for i in range(2,len(cost)):dp[i] = min(dp[i-1],dp[i-2])+cost[i]print(dp)return min(dp[-1],dp[-2])sol =Solution()
cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
sol.minCostClimbingStairs(cost)
c++:
class Solution {
public:int minCostClimbingStairs(vector<int>& cost) {int n = cost.size();vector<int> dp(n, 0);dp[0] = cost[0];dp[1] = cost[1];for(int i=2; i<n; i++){dp[i] = min(dp[i-1], dp[i-2]) + cost[i];}return min(dp[n-1], dp[n-2]);}
};
二十五:#一个四位数,如1024,1004,打印出他们的中文形式,如果一千零二十四,一千零四
a=9002
number_key={'0':'零','1':'一','2':'二','3':'三','4':'四','5':'五','6':'六','7':'七','8':'八','9':'九'}
c=''
if a%1000:for i,_ in enumerate(str(a)):while(i==0):c+=number_key[str(a)[i]]+'千'breakwhile(i==1):if str(a)[i]=='0' and str(a)[i]==str(a)[i+1]:c+=number_key[str(a)[i]]breakif str(a)[i]=='0' and str(a)[i]!=str(a)[i+1]:c+=number_key[str(a)[i]]+number_key[str(a)[i+1]]+'十'breakif str(a)[i] !='0' and str(a)[i+1]=='0':c+=number_key[str(a)[i]]+'百'breakelse:c+=number_key[str(a)[i]]+'百'+number_key[str(a)[i+1]]+'十'breakwhile(i==3):if str(a)[i]=='0':breakelse:c += number_key[str(a)[i]]break
else:c+=number_key[str(a)[0]]+'千'
print(c)
二十六:#找一串最长字符串 不含数字
#找一串最长字符串 不含数字
str1 = "abc123abcd234abcdefgha324adsdawqdasdaseqqwe345abchded"#第一种解法
#空间换时间做法 O(n)
all_count=[]
count=''
flag=0
for i in str1:if i.isdigit():flag=1if len(count):all_count.append(count)count=''else:flag=0count+=iprint(all_count)
num=[len(i) for i in all_count]
print(all_count[num.index(max(num))])
二十七:# 给定一行字符串,求出这行字符串中出现频率最高的字符,字符串中含有标点符号, # 字符不区分大小写。如果出现频率相同时,输出先出现在字符串中的字符。
s='AbAdefg ahigkl Mnopq rstu o v wBBBBBB!'a={s[0]:1}
for i in s[1:]:if i !=' ':if i in a:a[i]+=1else:a[i]=1print(a)print(a.items())
#a.items() 将dict变成list
b=sorted(a.items(),key=lambda x:x[1])
print(b)
print(b[-1][0])
print(b[-1][1])
二十八:#给出一个字符串,然后计算字符串中数字的和,
s=input()
# s='ssddd-12jijij-12hi-12'
a=''
for i in s:if i.isdigit() or i=='-':a+=ielse:a+='+'
print(a)if '-' in a:print(eval(a))
else:print(int(a))
eval知识补充:
x = 7
print(eval( '3 * x' ))
print(eval('2 +++- 2'))
二十九:#有一对奶牛,从出生后的第四年开始生小牛,每次生一对小牛, # 问现在有m对小牛,在第n年后有多少奶牛?
def cal(n):if n==None:return Noneif n<=3:return 1else:return cal(n-3)+cal(n-1) #上一年的牛 + 今年出生的牛n=4
m=2
print(cal(n))
三十:渔夫捕鱼
# A、B、C、D、E五人在某天夜里合伙捕鱼 最后疲惫不堪各自睡觉
# 第二天A第一个醒来 他将鱼分为5份 扔掉多余的1条 拿走自己的一份
# B第二个醒来 也将鱼分为5份 扔掉多余的1条 拿走自己的一份
# 然后C、D、E依次醒来也按同样的方式分鱼 问他们至少捕了多少条鱼
total=6
while True:enough=Truesingle_fish=totalfor person in range(5):if (single_fish -1) % 5==0:print('before single_fish=', single_fish)single_fish=(single_fish-1)//5*4print('after single_fish=', single_fish)else:enough=Falsebreakif enough:print('total=', total)breaktotal+=5
32.删除排序数组中的重复项
class Solution:def removeDuplicates(self, nums):# temp=0# n = len(nums)# for i in range(1,n):# if nums[i]==nums[i-1]:# temp+=1# return n-tempj = 0for i in range(1, len(nums)):if nums[i] != nums[j]:j += 1nums[j] = nums[i]print(nums)return j + 1nums = [1, 1, 2]
sol = Solution()
res = sol.removeDuplicates(nums)
print('==res:', res)
三十三.给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度。给定 nums = [1,1,1,2,2,3],函数应返回新长度 length = 5, 并且原数组的前五个元素被修改为 1, 1, 2, 2,3 。
nums = [1,1,1,2,2,3,3,3,4]class Solution(object):def removeDuplicates(self, nums):""":type nums: List[int]:rtype: int"""if len(nums)<=2:return len(nums)k=2for i in range(k,len(nums)):if nums[i]!=nums[k-1] or nums[i]!=nums[k-2]:nums[k]=nums[i]k+=1return ksol=Solution()
k=sol.removeDuplicates(nums)
print(k)
print(nums[:k])
三十四:给定一个按照升序排列的整数数组 nums
,和一个目标值 target
。找出给定目标值在数组中的开始位置和结束位置。
nums = [5,7,7,8,8,10]
target = 8
def solution(nums,target):a=[]#O(N)时间复杂度for i in range(len(nums)):if target==nums[i]:a.append(i)if len(a)==0:a=[-1,-1]return a
res=solution(nums,target)
print('res=',res)#O(log(N))时间复杂度 双指针查找
def solution(nums,target):low=0high=len(nums)-1while(low<=high):if target==nums[low] and target==nums[high]:return [low,high]elif target!=nums[low]:low+=1elif target!=nums[high]:high-=1return [-1,-1]
res=solution(nums,target)
print('res=',res)
三十五:给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。你可以假设数组中无重复元素。
示例 1:
输入: [1,3,5,6], 5
输出: 2
#时间复杂度O(log(N))
nums=[3,4,5,6,7]
target=9
def searchInsert(nums, target):low=0high=len(nums)while(low<high):mid = low + (high - low) // 2# print('mid:',mid)if nums[mid]>target or nums[mid]==target:high=midelse:low=mid+1return lowres=searchInsert(nums,target)
print('res:',res)#O(N)时间复杂度
nums=[3,4,5,6,7]
target=1
def searchInsert(nums, target):for i in range(len(nums)):if nums[i]>target:return iif nums[i]==target:return ireturn len(nums)res=searchInsert(nums,target)
print('res:',res)
三十六.给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字
candidates = [2,3,6,7]
target = 7
所求解集为:
[[7],[2,2,3]
]
# #给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合
candidates = [2,4,6]
target = 7def combinationSum(candidates, target):results=[]for i,num in enumerate(candidates):if target==num:results.append([num])elif num<target:print('num:',num)result_son=combinationSum(candidates[i:],target-num)print('result_son:',result_son)for result in result_son:result.append(num)results.append(result)return resultsres=combinationSum(candidates,target)
print('res:',res)
三十七.给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。candidates 中的每个数字在每个组合中只能使用一次。
candidates = [8,10]
target = 8
class Solution:def combinationSum2(self, candidates, target):candidates.sort()print('candidates:',candidates)res=[]self.addsort(candidates,target,res,[])return resdef addsort(self,candidates,target,res,cur):for i in range(len(candidates)):if target==candidates[i]:if cur+[candidates[i]] not in res:res.append(cur+[candidates[i]])print('res:',res)elif candidates[i]>target:returnelse:self.addsort(candidates[i+1:],target-candidates[i],res,cur+[candidates[i]])solv=Solution()
res=solv.combinationSum2(candidates,target)
print('res:',res)
三十八.合并矩形框算法
class Solution:def merge(self, intervals,threshold):# intervals.sort(key=lambda x: x[0])# print(intervals)merged = []for interval in intervals:# print('interval:',interval)#x2减去下一个框的x1if not merged or abs(merged[-1][2]-interval[0]) <threshold :if len(merged):merged[-1][-2:] = interval[-2:]else:merged.append(interval)else:merged.append(interval)print('merged:',merged)return merged# a=[[1,3],[2,6],[12,10],[15,18]]
import numpy as np
import cv2
points=np.array([[0,0,20,20],[30,0,20,50],[90,0,70,20],[220,0,200,200],[240,0,220,200],[250,230,260,280]])
img=np.zeros((500,500))
#before merge
for point in points:x1,y1,x2,y2=pointcv2.rectangle(img,(x1,y1),(x2,y2),color=(255,255,255),thickness=1)
cv2.imwrite('img_before.jpg',img)#after merge
sol=Solution()
res=sol.merge(points,threshold=100)
print(res)
#before merge
# for point in res:
# x1,y1,x2,y2=point
# cv2.rectangle(img,(x1,y1),(x2,y2),color=(255,255,255),thickness=1)
# cv2.imwrite('img_after.jpg',img)
三十九.求众数
class Solution(object):def majorityElement(self, nums):""":type nums: List[int]:rtype: int"""res={}for num in nums:if num not in res:res[num]=1else:res[num]+=1index=sorted(res,key=lambda i:res[i])return index[-1]a=[1,1,1,2,2,3,3,3,3,3]
sol=Solution()
res=sol.majorityElement(a)
print('res:',res)
四十.缺失的第一个正数
class Solution(object):def firstMissingPositive(self, nums):""":type nums: List[int]:rtype: int"""num=1for i in range(len(nums)):if num in nums:num+=1return numa=[1,2,3,-1]
sol=Solution()
res=sol.firstMissingPositive(a)
print('res:',res)
四十二.牛顿法开跟号
class Solution(object):def mySqrt(self, a):""":type x: int:rtype: int"""x0=awhile x0*x0>a:x0=(x0*x0+a)/(2*x0)return int(x0)sol=Solution()
x=5
res=sol.mySqrt(x)
print('res:',res)
四十三.堆栈实现加减乘除(逆波兰表达式求值)
class Solution(object):def evalRPN(self, tokens):""":type tokens: List[str]:rtype: int"""stack = []cal = {"+" : lambda x,y :x+y, "-" : lambda x,y : x-y, "*" : lambda x,y : x*y, "/" : lambda x,y : int(x/y)}for i in tokens:print('stack:',stack)if i not in ["+","-","*","/"]:stack.append(int(i))else:b = stack.pop()a = stack.pop()stack.append(cal[i](a,b))return stack[0]a=["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
sol=Solution()
res=sol.evalRPN(a)
print('res:',res)
四十五.给定一个字符串,逐个翻转字符串中的每个单词。
输入: " hello world! "
输出: "world! hello"
class Solution(object):def reverseWords(self, s):""":type s: str:rtype: str"""return " ".join(s.split()[::-1])
49.给定两个数组,编写一个函数来计算它们的交集。
class Solution(object):def intersection(self, nums1, nums2):""":type nums1: List[int]:type nums2: List[int]:rtype: List[int]"""inter = set(nums1) & set(nums2)res = []for i in inter:res += [i] * min(nums1.count(i), nums2.count(i))return resnums1 = [1,2,3,2,1]
nums2 = [2,3,2]
sol=Solution()
res=sol.intersection(nums1,nums2)
print('res:', res)
五十.给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色
https://leetcode-cn.com/problems/sort-colors/
利用三指针,(p0, p2 和curr)来分别追踪0的最右边界,2的最左边界和当前考虑的元素。
class Solution(object):def sortColors(self, nums):""":type nums: List[int]:rtype: None Do not return anything, modify nums in-place instead."""p0=0curr=0p2=len(nums)-1while curr<=p2:if nums[curr]==0:nums[p0],nums[curr]=nums[curr],nums[p0]p0+=1curr+=1elif nums[curr]==1:curr += 1else:#nums[curr]==2nums[p2],nums[curr] = nums[curr],nums[p2]p2 -= 1print(nums)return numsnums=[2,0,2,1,1,0]
sol=Solution()
sol.sortColors(nums)
51.验证回文字符串
解法1:双指针
class Solution(object):def isPalindrome(self, s):""":type s: str:rtype: bool"""i = 0j = len(s)-1while i<j:while i < len(s) and not s[i].isalnum():i += 1while j>=0 and not s[j].isalnum():j-=1#多个符号时 i跳得太多if i>j:return Trueif s[i].upper()!=s[j].upper():return Falseelse:i+=1j-=1#while外面自然是i>=jreturn Trues= ""
sol = Solution()
res = sol.isPalindrome(s)
print('res:',res)
解法2:
class Solution(object):def isPalindrome(self, s):""":type s: str:rtype: bool"""s = ''.join(list(filter(str.isalnum,s))).lower()print('s:',s)return s==s[::-1]
五十二,验证回文串2,字符串只包含从 a-z 的小写字母。字符串的最大长度是50000。
https://leetcode-cn.com/problems/valid-palindrome-ii/
class Solution(object):def validPalindrome(self, s):""":type s: str:rtype: bool"""if s==s[::-1]:return Truel=0r=len(s)-1while l<r:if s[l]==s[r]:l+=1r-=1else:part1=s[l+1:r+1]part2=s[l:r]# print('part1',part1)# print('part2',part2)return part1 == part1[::-1] or part2 == part2[::-1]s= "abca"
sol = Solution()
res = sol.validPalindrome(s)
print('res:',res)
五十三.汉诺他问题
如果只有一个A直接给C,当大与1个时,将n-1暂时给B,剩下的最大的给C,然后再将n-1给C.
def hannota(n,A,B,C):if n==1:print(A+'->'+C)else:hannota(n - 1,A,C,B)print(A + '->' + C)hannota(n - 1, B, A, C)if __name__ == '__main__':n=2A='A'B='B'C='C'hannota(n,A,B,C)
五十四.有效的数独 要求:行 ,列和3x3只能出现一个数字一次
https://leetcode-cn.com/problems/valid-sudoku/
class Solution(object):def isValidSudoku(self, board):""":type board: List[List[str]]:rtype: bool"""# init datarows = [{} for i in range(9)]columns = [{} for i in range(9)]boxes = [{} for i in range(9)]# print(rows)# print(rows[2].get(3, 0))rows[2][3]=rows[2].get(3, 0)# print(rows)for i in range(9):for j in range(9):num = board[i][j]if num != '.':num = int(num)box_index = (i // 3) * 3 + j // 3# keep the current cell valuerows[i][num] = rows[i].get(num,0) + 1columns[j][num] = columns[j].get(num,0)+1boxes[box_index][num]=boxes[box_index].get(num,0)+1if rows[i][num]>1 or columns[j][num]>1 or boxes[box_index][num]>1:return Falsereturn Trueboard=[["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]
]
sol = Solution()
res = sol.isValidSudoku(board)
print('res:')
print(res)
五十五.给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。
https://leetcode-cn.com/problems/contains-duplicate-ii/
class Solution:def containsNearbyDuplicate(self, nums, k):""":type nums: List[int]:type k: int:rtype: bool"""nums_len = len(nums)if nums_len <= 1:return False#key存放列表值,value存放位置索引nums_dict = {}for i in range(nums_len):print(nums_dict)if nums[i] in nums_dict:if i-nums_dict[nums[i]] <= k:return Truenums_dict[nums[i]] = ireturn Falsenums = [1,2,3,1]
k = 3
sol = Solution()
res = sol.containsNearbyDuplicate(nums,k)
print('res:')
print(res)
五十六.长度最小的子数组
思路:双指针 滑动窗口
class Solution:def minSubArrayLen(self, s, nums):i = 0j = 0ans = float('inf')while j < len(nums):# 向右滑动 直到大于sif sum(nums[i:j + 1]) < s:# Sum=sum(nums[begin:right])j += 1# 找到滑窗之和大于s的地方else:# 当前长度若是小于之前的 则更新if j - i < ans:ans = j - i + 1i += 1return 0 if ans == float('inf') else anss = 7
nums = [2,3,1,2,4,3]
sol = Solution()
res = sol.minSubArrayLen(s, nums)
print('==res:', res)
五十七.滑动窗口找到长度最长的子数组 <=4 [3,1,2,1] 最长为[1,2,1]
class Solution(object):def minSubArrayLen(self, s, nums):""":type s: int:type nums: List[int]:rtype: int"""final_begin=0final_end=0begin=0right=0ans=0#float('inf')while right<len(nums):# print('begin:', begin)# print('right:', right)# print(nums[begin:right+1])#向右滑动 直到大于sif sum(nums[begin:right+1]) <= s:# Sum=sum(nums[begin:right])right+=1# 当前长度若是大于之前的 则更新if right-begin>ans:ans = right-begin +1final_begin=beginfinal_end=right#找到滑窗之和大于s的地方else:begin+=1print('final_begin:',final_begin)print('final_end:',final_end)print(nums[final_begin:final_end+1])return 0 if ans==float('inf') else anss = 4
nums = [3,1,2,1]
# s = 3
# nums = [1,1]
sol=Solution()
res=sol.minSubArrayLen(s,nums)
print('res:',res)
五十九.将矩阵存在0的行列都置零
https://leetcode-cn.com/problems/set-matrix-zeroes
import numpy as npclass Solution(object):def setZeroes(self, matrix):""":type matrix: List[List[int]]:rtype: None Do not return anything, modify matrix in-place instead."""print(np.array(matrix))# matrix=np.array(matrix)is_col=False#记录为0的索引,并此处的行头和猎头置为零for i in range(len(matrix)):if matrix[i][0]==0:is_col=Truefor j in range(1,len(matrix[0])):# print(matrix[i][j])if matrix[i][j]==0:matrix[0][j] = 0matrix[i][0] = 0# breakprint(np.array(matrix))for i in range(1,len(matrix)):for j in range(1,len(matrix[0])):if not matrix[i][0] or not matrix[0][j]:matrix[i][j]=0print(np.array(matrix))# 对第一个数存在0将这一列置为0print(np.array(matrix))if matrix[0][0] == 0:for j in range(len(matrix[0])):matrix[0][j] = 0#对第一列存在0将整列置零if is_col:for i in range(len(matrix)):matrix[i][0]=0print(np.array(matrix))return matrix# matrix = [[1,1,1],
# [1,0,1],
# [1,1,1]]
# matrix=[[0,1,2,0],
# [3,4,5,2],
# [1,3,1,5]]
matrix=[[1,1,1],[0,1,2]]
sol=Solution()
res=sol.setZeroes(matrix)
print('res:',res)
六十.给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
https://leetcode-cn.com/problems/4sum/
class Solution(object):def fourSum(self, nums, target):""":type nums: List[int]:type target: int:rtype: List[List[int]]"""nums.sort()# print('nums:',nums)ans = set()for i in range(len(nums)-3):#第一层循环到达三个数之前for j in range(i+1,len(nums)-2):#最后两个数需要固定left=j+1 #左指针right=len(nums)-1 #右指针while(right>left):temp=nums[i]+nums[j]+nums[left]+nums[right]if temp==target:ans.add((nums[i],nums[j],nums[left],nums[right]))left+=1right-=1elif temp>target:right-=1else:left+=1# print('ans:',ans)ans = sorted(ans)res=[]for i in ans:res.append(i)# print('res:',res)return resnums = [-3,-2,-1,0,0,1,2,3]
target = 0
sol=Solution()
res=sol.fourSum(nums, target)
print('res:',res)
61.无重复字符的最长子串
思路1滑动窗口:
class Solution:def lengthOfLongestSubstring(self, s):left, right = 0, 0dict_ = {}res = 0while right < len(s):dict_[s[right]] = dict_.get(s[right], 0) + 1while dict_[s[right]] > 1:dict_[s[left]] -= 1left += 1right += 1res = max(right - left, res)print('==res:', res)return ress = "abcabcbb"
sol = Solution()
sol.lengthOfLongestSubstring(s)
思路2.hash
class Solution:def lengthOfLongestSubstring(self, s: str) -> int:occ = set()n = len(s)# 右指针,初始值为 -1,相当于我们在字符串的左边界的左侧,还没有开始移动start, ans = -1, 0for i in range(n):# print('===occ:', occ)if i != 0:# 左指针向右移动一格,移除一个字符occ.remove(s[i - 1])while start + 1 < n and s[start + 1] not in occ:# 不断地移动右指针occ.add(s[start + 1])start += 1# 第 i 到 rk 个字符是一个极长的无重复字符子串ans = max(ans, start - i + 1)return ans
六十二.串联所有单词的子串
给定一个字符串s和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。
#通过滑动去裁剪主串得到子串,然后子串与需要匹配的字符串数组去统计出现的个数,个数相等即找到
class Solution:def findSubstring(self, s, words):from collections import Counterif not s or not words:return []all_len = len(''.join(words))print('==all_len:', all_len)n = len(s)words = Counter(words)print('==words', words)res = []for i in range(0, n-all_len+1):temp = s[i:i+all_len]# print(temp)c_temp=[]for j in range(0, all_len,all_len//len(words)):c_temp.append(temp[j:j+all_len//len(words)])# print(c_temp)if Counter(c_temp)==words:res.append(i)# print('res:', res)return resif __name__ == '__main__':solution = Solution()# s = "abc"# words = ["a"]s = "barfoothefoobarman"words = ["foo", "bar"]res = solution.findSubstring(s, words)print('res:', res)
六十三.给你一个字符串 S、一个字符串 T,请在字符串 S 里面找出:包含 T 所有字母的最小子串。
输入: S = "ADOBECODEBANC", T = "ABC"
输出: "BANC"
双指针法:
from collections import Counterdef minWindow(s, t):""":type s: str:type t: str:rtype: str"""if not t or not s:return ""dict_t = Counter(t)print('==dict_t:', dict_t)required = len(dict_t)l, r = 0, 0formed = 0window_counts = {}# ans tuple of the form (window length, left, right)ans = float("inf"), None, Nonewhile r < len(s):character = s[r]window_counts[character] = window_counts.get(character, 0) + 1print('==window_counts:', window_counts)#s = "ABAACBAB"#t = "ABC"#相等的话就加1if character in dict_t and window_counts[character] == dict_t[character]:formed += 1#找到满足要求的 进行存储while l <= r and formed == required:character = s[l]print('==character:', character)# Save the smallest window until now.if r - l + 1 < ans[0]:ans = (r - l + 1, l, r)#window_counts[character] -= 1#左指针向右移动 出现不符合的就减一if character in dict_t and window_counts[character] < dict_t[character]:formed -= 1#移动左指针l += 1#右指针移动r += 1return "" if ans[0] == float("inf") else s[ans[1]:ans[2] + 1]S = "ABAACBAB"
T = "ABC"
res = minWindow(S, T)
print('res:', res)
六十四.替换子串得到平衡字符串
有一个只含有'Q'
, 'W'
, 'E'
,'R'
四种字符,且长度为 n
的字符串。假如在该字符串中,这四个字符都恰好出现n/4
次,那么它就是一个「平衡字符串」。
输入:s = "QQWE"
输出:1
解释:我们需要把一个 'Q' 替换成 'R',这样得到的 "RQWE" (或 "QRWE") 是平衡的。
import collections
class Solution(object):def balancedString(self, s):"""python版本:type s: str:rtype: int"""cnt = collections.Counter(s)res = n = len(s)left, avg = 0, n//4for right, c in enumerate(s):# print('c:', c)#一直进行字符减操作cnt[c] -= 1print('cnt:', cnt)#直到n//4大于单个字符的个数 说明右边界找到 在对左边界进行右移 找最小的长度while left < n and all(avg >= cnt[x] for x in 'QWER'):res = min(res, right - left + 1)print('res:', res)cnt[s[left]] += 1print('==cnt:', cnt)left += 1print('res:', res)return ressol = Solution()s = 'WQWRQQQW'
sol.balancedString(s)
六十八.不邻接植花
图着色问题
# 1、构建邻接矩阵;
# 2、将1的颜色置为1,从2开始遍历邻接矩阵;
# 3、每一次遍历,新建一个颜色集合([1,2,3,4]),取出key对应的花园代号,遍历代号。
# 如果该代号花园已经有颜色了,取出其颜色,从颜色集合中去掉;如果该花园没有颜色,跳过;
# 全部代号遍历结束后,取颜色集合第一个颜色作为当前key 的颜色,存入结果中;
# 4、反复计算更新结果,最后输出结果;class Solution(object):def gardenNoAdj(self, N, paths):""":type N: int:type paths: List[List[int]]:rtype: List[int]"""recorder = {}for i in range(1, N+1, 1):recorder[str(i)] = []for path in paths:recorder[str(path[0])].append(path[1])recorder[str(path[1])].append(path[0])print('===recorder:', recorder)#将1的颜色置为1,从2开始遍历result = [1]for i in range(2, N+1, 1):colors = [1, 2, 3, 4]sub_nodes = recorder[str(i)]print('==sub_nodes:', sub_nodes)for sub_node in sub_nodes:if sub_node > len(result):#没有颜色,跳过continueelse:if result[sub_node-1] in colors:#有颜色进行移除colors.remove(result[sub_node-1])result.append(colors[0])print('==result:', result)return result# N = 3
# paths = [[1, 2],
# [2, 3],
# [3, 1]]N = 4
paths = [[1, 2],[3, 4]]
sol = Solution()
sol.gardenNoAdj(N, paths)
七十.找到小镇的法官
思路:统计所有人的入度和出度信息,将满足出度为0,入度为 N - 1的节点输出。
#维护两个列表一个用于记录入度,一个用于记录出度,满足入度为N-1, 出度为0的就是法官
class Solution:def findJudge(self, N, trust):input_degree = [0]*Nouput_degree = [0]*Nfor trust_ in trust:input_degree[trust_[0] - 1] += 0input_degree[trust_[1] - 1] += 1ouput_degree[trust_[0] - 1] += 1ouput_degree[trust_[1] - 1] += 0print('==input_degree:', input_degree)print('==ouput_degree:', ouput_degree)for i in range(len(input_degree)):if input_degree[i] == N-1 and ouput_degree[i] == 0:return i+1return -1
# N = 2
# trust = [[1, 2]]
# N = 3
# trust = [[1, 3],
# [2, 3]]
# N = 3
# trust = [[1,3],
# [2,3],
# [3,1]]
N = 4
trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
sol = Solution()
res = sol.findJudge(N, trust)
print(res)
#维护一个列表用于记录入度与出度的差值,差值为N-1, 就是法官
class Solution:def findJudge(self, N, trust):count = [0]*Nfor trust_ in trust:count[trust_[0] - 1] -= 1count[trust_[1] - 1] += 1print('==count:', count)for i in range(len(count)):if count[i] == N-1:return i+1return -1
# N = 2
# trust = [[1, 2]]
# N = 3
# trust = [[1, 3],
# [2, 3]]
# N = 3
# trust = [[1, 3],
# [2, 3],
# [3, 1]]
N = 4
trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
sol = Solution()
res = sol.findJudge(N, trust)
print(res)
七十一.课程安排 IV
利用弗洛伊德算法找出节点与节点之间的路径,计算出邻接矩阵。
#佛罗伊德算法:dp矩阵先进行初始化,用两个节点是否经过中间节点,来更新中间节点的dp矩阵
class Solution:def checkIfPrerequisite(self, n, prerequisites, queries):dp = [[0 for i in range(n)] for j in range(n)]print(dp)for prerequisite in prerequisites:dp[prerequisite[0]][prerequisite[1]] = 1print(dp)for k in range(n):#k代表中间节点for i in range(n):#i开始节点for j in range(n):#j终止节点if dp[i][k] ==1 and dp[k][j]==1:dp[i][j] = 1print(dp)res = []for querie in queries:# print(dp[querie[0]][querie[-1]])res.append(dp[querie[0]][querie[-1]])return res
n = 5
prerequisites = [[0, 1],[1, 2],[2, 3],[3, 4]]
queries = [[0, 4],[4, 0],[1, 3],[3, 0]]sol = Solution()
res = sol.checkIfPrerequisite(n, prerequisites, queries)
print('res:', res)
七十四.划分为k个相等的子集
# 1、先求出数组的平均数 avg,如果平均数 avg 不为整数,也就是说数组的数字总和不能平均的分为 k 份,那么直接返回 false;
#
# 2、创建一个布尔数组 flag,用来记录 nums 数组中数字的状态(已用还是未用)。 temp 的作用是记录当前子集的数字总和,temp 初始为 avg ,当 temp 等于 0 时,当前这个子集也就可以确定了。index 是用来记录遍历数组时从哪个位置开始遍历,以防将前面的数字重新计算。
#
# 3、当 temp = 0 的时候,也就是新一个子集求解完,那么继续求解下一个子集,k - 1,temp 重新置为 avg;当 temp != 0 时,就是子集还未求解完,那么继续求解子集,继续从数组中取数字,递归求解。
#
# 4、当 k 个子集全部求解完,返回 true,如果一直求解不出,则返回 false。
class Solution:def canPartitionKSubsets(self, nums, k):if sum(nums) % k != 0:#先判断能不能分成k组return Falseavg = sum(nums)/kflag = [0]*len(nums)print('==flag:', flag)return self.helper(nums, flag, avg, k, avg, 0)def helper(self, nums, flag, avg, k, temp, index):if k == 0:#k为0说明划分好了k个子集return Trueif temp == 0:#平均数减去子集的剩下数字.如果为0继续求解下一个子集,k-1,temp重置为avg,下标index也重置为0return self.helper(nums, flag, avg, k - 1, avg, 0)#划分当前子集for i in range(index, len(nums)):if flag[i]:#已经使用过continueflag[i] =1 #标记使用print('==flag:', flag)# 递归调用子过程,父过程是否为true,取决于子过程的结果if (temp - nums[i]) >= 0 and self.helper(nums, flag, avg, k, temp - nums[i], index + 1):return True#往下执行 说明没有使用 重置为0flag[i] = 0return Falsenums = [4, 3, 2, 3, 5, 2, 1]
k = 4
target, rem = divmod(sum(nums), k)
print('==target:', target)
print('==rem:', rem)
# nums = [129, 17, 74, 57, 1421, 99, 92, 285, 1276, 218, 1588, 215, 369, 117, 153, 22]
# k = 3
sol = Solution()
res = sol.canPartitionKSubsets(nums, k)
print('=res:', res)