所有的题型目录在下面的链接
LeetCode相关典型题解合集(两百多道题)
双指针
167. Two Sum II - Input array is sorted (Easy)
思路:第一种方法是双指针,第二个是二分
这里我用的是双指针。首先一个指向数组头a,一个指向数组的尾部b。
有三种情况。
- 第一种是两个数相加小于target,此时a++
- 第二种是两个数相加大于target,此时b–
- 第三种是两个数相加等于target,此时创建一个vector然后添加值
vector<int> twoSum(vector<int>& numbers, int target) {
int a=0;
int b=numbers.size()-1;
vector<int> res(2,-1);
while(a!=b){
if(numbers[a]+numbers[b]<target){
a++;
}
else if(numbers[a]+numbers[b]>target){
b--;
}
else{
res[0]=a+1;
res[1]=b+1;
return res;
}
}
return res;
}
633. Sum of Square Numbers (Easy)
对于一个数c,可以对其开方,这样子可以有一个尾端值
设a=0,b=sqrt©
然后老样子a++,b–
结束循环的前提是a>b才行
bool judgeSquareSum(int c) {
long int a=0;
long int b=sqrt(c);
while(a<=b){
if(a*a+b*b<c){
a++;
}
else if(a*a+b*b>c){
b--;
}else{
return true;
}
}
return false;
}
345. Reverse Vowels of a String (Easy)
string reverseVowels(string s) {
int a=0;
int b=s.size()-1;
char temp1;
char temp2;
string set="aeiouAEIOU";
while(a<b){
if(set.find(s[a])==string::npos){
a++;
continue;
}else{
temp1=s[a];
}
if(set.find(s[b])==string::npos){
b--;
continue;
}else{
temp2=s[b];
}
s[a++]=temp2;
s[b--]=temp1;
}
return s;
}
680. Valid Palindrome II (Easy)
bool validPalindrome(string s) {
int a=0;
int b=s.size()-1;
while(a<b){
if(s[a]!=s[b]){
return ispalindrome(s,a,b-1) || ispalindrome(s,a+1,b);
}
a++;
b--;
}
return true;
}
bool ispalindrome(string s,int a,int b){
while(a<b){
if(s[a++]!=s[b--]){
return false;
}
}
return true;
}
88. Merge Sorted Array (Easy)
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int sum=m+n-1;
while(n>0){
if(m==0){
nums1[sum--]=nums2[--n];
}
else if(nums2[n-1]>nums1[m-1]){
nums1[sum--]=nums2[--n];
}
else{
nums1[sum--]=nums1[--m];
}
}
}
141. Linked List Cycle (Easy)
bool hasCycle(ListNode *head) {
ListNode *slow=head;
ListNode *quick=head;
while(slow->next!=nullptr){
slow=slow->next;
quick=quick->next->next;
if(slow=quick){
return true;
}
}
return false;
}
524. Longest Word in Dictionary through Deleting (Medium)
string findLongestWord(string s, vector<string>& d) {
int max_number=0;
bool flag=false;
int max_index;
for(int i=0;i<d.size();i++){
//双指针
int m=0;
int n=0;
while(m<s.size()){
if(s[m]==d[i][n]){
m++;
n++;
}else{
m++;
}
}
if(n==d[i].size()){//判断n是否是字典中元素的长度,如果是说明可以找到
flag=true;
if(n>max_number){//判断是否是最长的字符串,如果有多个最长要判断字典序
max_number=n;
max_index=i;
}else if(n==max_number){
//判断字典序
for(int num=0;num<n-1;num++){
if(d[max_index][num]>d[i][num]){
max_index=i;
break;
}else if(d[max_index][num]==d[i][num]){
continue;
}
break;
}
}
}
}
if(flag==false){
return "";
}
else {
return d[max_index];
}
}