第11题
#暴力算法
#必然超时
#无奈作者我没有文化,知道超时也只能写暴力算法
#52 / 60 个通过测试用例
#状态:超出时间限制
from typing import List
class Solution:
def maxArea(self, height: List[int]) -> int:
length=len(height)
maxdata=0
nowdata=0
for i in range(0,length):
for j in range(0,length):
nowdata=(j-i+1)*( height[i] if height[i]<height[j] else height[j])
if maxdata < nowdata:
maxdata=nowdata
return maxdata
#稍微做了一点优化,但是还是超时 草
# 53 / 60 个通过测试用例
# 状态:超出时间限制
# 提交时间:几秒前
class Solution:
def maxArea(self, height: List[int]) -> int:
length=len(height)
maxdata=0
nowdata=0
for i in range(0,length):
flag=True
for j in range(length-1,i-1,-1):
if flag and height[j]>=height[i]:
flag=False
temp=(j-i)*height[i]
maxdata=maxdata if maxdata>temp else temp
elif height[j]<height[i]:
temp=(j-i)*height[j]
maxdata = maxdata if maxdata > temp else temp
else:
continue
return maxdata
#双指针法
#用时132mx 内存24MB
class Solution:
def maxArea(self, height: List[int]) -> int:
left=0
right=len(height)-1
maxdata=0
while left<right:
if(height[left]<height[right]):
shortheight = height[left]
left+=1
else:
shortheight=height[right]
right-=1
temp=(right-left+1)*shortheight #因为left进行了+1 或者right-1 导致这个数变小
maxdata=maxdata if maxdata>temp else temp
return maxdata
第12题
#讲道理
#这道题应该修改为easy
#执行用时:48 ms
#内存消耗:15 MB
#在所有 Python3 提交中击败了20.19%的用户
class Solution:
def intToRoman(self, num: int) -> str:
#整数转化为罗马数字
str1=""
datalist=[1000,900,500,400,100,90,50,40,10,9,5,4,1]
TrunRoman=["M","CM","D","CD","C","XC","L","XL","X",'IX',"V","IV","I"]
i=0
#print(datalist)
#print(TrunRoman)
while num>0:
#print(len(datalist))
while i<len(datalist) and num>=datalist[i]:
num=num-datalist[i]
str1+=(TrunRoman[i])
i+=1
return str1
第13题
#简单题
#无难度
class Solution:
def romanToInt(self, s: str) -> int:
length=len(s)
datalist=[1000,500,100,50,10,5,1]
TrunRoman=["M","D","C","L","X","V","I"]
nowplace=0
lastplace=0
sum=0
for i in range(0,length):
nowplace=TrunRoman.index(s[i])
if nowplace<lastplace: #这表明上一个字符代表的数字更小
sum-=datalist[lastplace]*2
sum+=datalist[nowplace]
lastplace=nowplace
return sum
第14题
#简单题 pass
#执行用时:28 ms
#python
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
nums = len(strs)
if nums == 0 or not len(strs[0]):
return ""
nowplace = 0
answer = ""
for i in range(0, len(strs[0])): # 检测0号单元所有角色
flag=True
for j in range(0, nums):
if i < len(strs[j]) and strs[j][i] == strs[0][i]:
pass
else:
flag=False
break
if flag:
answer += strs[0][i]
else:
break
return answer
第15题
#究极使用字典暴力算法
#无脑中的无脑
#就这样还能ac,实属当代奇才
#用时 7000ms 超越5%
#python
from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
count_number = {}
answer_dir={}
for i in range(0, len(nums)):
if count_number.get(nums[i]) == None:
count_number[nums[i]] = 1
else:
count_number[nums[i]] +=1
#print(count_number)
for x in count_number.keys():
for y in count_number.keys():
z=0-x-y
temp_dir={}
self.Process_1(x, temp_dir)
self.Process_1(y, temp_dir)
self.Process_1(z, temp_dir)
if(self.Process_2(x,temp_dir,count_number) and self.Process_2(y,temp_dir,count_number) and self.Process_2(z,temp_dir,count_number) ):
self.Process_3(x,y,z,answer_dir)
else:
continue;
answer=[list(an) for an in answer_dir.keys()]
#print(answer)
return answer
def Process_1(self,x,temp_dir):
if temp_dir.get(x):
temp_dir[x]+=1
else:
temp_dir[x]=1
def Process_2(self,x,temp_dir,count_numbers):
if count_numbers.get(x) and temp_dir[x]<=count_numbers[x]:
return True
else:
return False
def Process_3(self,x,y,z,answe_dir):
answer_temp=sorted([x,y,z])
print(answer_temp)
if not answe_dir.get(tuple(answer_temp)):
answe_dir[tuple(answer_temp)]=1
优化后的 双指针算法
//执行用时:22 ms
//内存消耗:42.8 MB
//java
class Solution {
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> answer=new ArrayList();
Arrays.sort(nums);
boolean preSuccess=false;
for(int i=0;i<nums.length-2;i++)
{
int left=i+1;
int right=nums.length-1;
if(nums[i]>0)
{
break;
}
if(preSuccess&&nums[i]==nums[i-1]) //上一次成功了 并且本次测算的 数字和上一次相同
{
//其必然导致结果重复
preSuccess=true;
continue;
}
boolean in_preSuccess=false;
preSuccess=false;
while(left<right)
{
if(nums[i]+nums[left]+nums[right]>0)
{
//表明 right太大
right--;
in_preSuccess=false;
}
else if(nums[i]+nums[left]+nums[right]<0)
{
left++;
in_preSuccess=false;
}
else //表明这组数据符合三数之和等于0
{
if(in_preSuccess&&nums[left-1]==nums[left])//如果内循环中上一次成功了,
//并且left向右移动两个值相等
{
in_preSuccess=true;
preSuccess=true;
left++;
}
else
{
List<Integer> answerx=new ArrayList<Integer>();
answerx.add(nums[i]);
answerx.add(nums[left]);
answerx.add(nums[right]);
//System.out.print(answerx);
left++;
answer.add(answerx);
in_preSuccess=true;
preSuccess=true;
}
}
}
}
//System.out.print(answer);
return answer;
}
}
第16题
//沿用上一题的双指针算法
//执行用时:4 ms
//内存消耗:37.9 MB
//java
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int smallplus= Integer.MAX_VALUE; //表明int的最大值
int resultanswer=0;
for(int i=0;i<nums.length-2;i++)
{
int left=i+1;
int right=nums.length-1;
while(left<right)
{
int temp=(target-nums[i]-nums[left]-nums[right]);
//System.out.println(temp);
if(smallplus>Math.abs(temp))
{
smallplus=Math.abs(temp);
resultanswer=nums[i]+nums[left]+nums[right];
}
if(temp>0) //表明三数之和较小
{
left++;
}
else if(temp<0)
{
right--;
}
else
{
return target;
}
}
}
return resultanswer;
}
}
第17题
#按照题目的要求编写程序即可
#32ms 15MB
#python
tel_numer = ["abc", "def", "ghi", "jkl", 'mno', 'pqrs', 'tuv', "wxyz"]
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
returnList=[]
if len(digits)==0:
return returnList
else:
for i in range(0,len(tel_numer[int(digits[0])-2])):
returnList.append(tel_numer[int(digits[0])-2][i])
#print(returnList)
for i in range(1,len(digits)):
returnList=self.process_1(digits[i],returnList)
# print(returnList)
return returnList
def process_1(self,number,returnList,):
length=len(returnList)
tempList=[]
for i in range(0,length):
for j in range(0,len(tel_numer[int(number)-2])): #对tel中对应数字的每一个字符进行枚举
tempList.append(returnList[i]+tel_numer[int(number)-2][j])
return tempList
第18题
#四数之和
#本质上就是三数之和plus版本
#再套一个循环就行了
#744ms 14.8MB
#python
class Solution:
def fourSum(self, nums, target: int) -> List[List[int]]:
nums.sort()
length = len(nums)
answer = {}
if len(nums) < 4:
return []
for i in range(0, length - 3):
temptarget = target - nums[i]
for j in range(i + 1, length - 2):
left = j + 1
right = length - 1
if j > i + 1 and nums[j] == nums[j - 1]:
continue
preSuccess = False
while left < right:
if nums[left] + nums[right] + nums[j] < temptarget:
left += 1
preSuccess = False
elif nums[left] + nums[right] + nums[j] > temptarget:
right -= 1
preSuccess = False
else:
if preSuccess and nums[left] == nums[left - 1]:
preSuccess = True
left += 1
else:
preSuccess = True
temptuple = (nums[i], nums[j], nums[left], nums[right])
if answer.get(temptuple):
left += 1
else:
answer[temptuple] = 1
return list(answer.keys())
第19题
//数据结构常见类型题
//8ms 10MB
//C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head->next==nullptr)
{
delete head;
return nullptr;
}
int length=0;
ListNode* temphead = head;
ListNode* temphead2 = head;
for (int i = 0; i < n; i++)
{
temphead2 = temphead2->next;
length++;
}
//让2号先跑n步
if(temphead2==nullptr)
{
return head->next;
}
ListNode* pre = temphead;
while (temphead2)
{
pre = temphead;
temphead2 = temphead2->next;
temphead = temphead->next;
length++;
}
ListNode* deletenode=pre->next;
pre->next = pre->next->next;
return head;
}
};
第20题
//简单题
//详细判定不想去改了 就这样吧
class Solution {
public:
bool isValid(string s) {
int length = s.length();
stack<char> p;
for (int i = 0; i < length; i++)
{
if (!p.empty() && this->isPIPEI(s[i],p.top()))
{
p.pop();
}
else
{
p.push(s[i]);
}
}
return p.empty();
}
bool isPIPEI(char a, char b)
{
// cout << a << " " << b << endl;
if (b == ')' || b == '}' || b == ']')
{
return false;
}
else
{
if ((b == '(' && a == ')') || (b == '[' && a == ']') || (b == '{' && a == '}'))
{
return true;
}
else{
return false;
}
}
}
};