1、有序数组中找两个数和等于某数
167. Two Sum II - Input array is sorted (Easy)
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
- Your returned answers (both index1 and index2) are not zero-based.
- You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
问题分析
采用双指针遍历数组,协调两个指针指向不同的位置来完成任务。
两个下标分别指向数组的头和尾,两数相加,如果小于目标值,左侧下标右移,如果大于目标元素,右侧下边左移,直到找到目标或者两下标相遇。
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int i=0,j=numbers.size()-1;
vector<int>vec;
while(i<j)
{
int sum=numbers[i]+numbers[j];
if(sum<target)
i++;
else if(sum>target)
j--;
else
{
vec.push_back(i+1);
vec.push_back(j+1);
break;
}
}
return vec;
}
};
2、两数平方和
633. Sum of Square Numbers(Easy)
Given a non-negative integer c, your task is to decide whether there’re two integers a and b such that a2 + b2 = c.
Example 1:
Input: 5
Output: True
Explanation: 1*1 + 2*2 = 5
Example 2:
Input: 3
Output: False
问题分析
方法一:
暴力搜索,不推荐这种方法,可能超时
class Solution {
public:
bool judgeSquareSum(int c) {
for (long a = 0; a * a <= c; a++)
{
for (long b = 0; b * b <= c; b++)
{
if (a * a + b * b == c)
return true;
}
}
return false;
}
};
方法二:
双指针,一前一后两个数,不断向中间靠近,查看二者平方和是否等于原数。
class Solution {
public:
bool judgeSquareSum(int c) {
long i=0;
long j=(long)sqrt(c);
while(i<=j)
{
long tmp=i*i+j*j;
if(tmp==c)
return true;
else if(tmp>c)
j--;
else
i++;
}
return false;
}
};
3、翻转字符串中的元音字符
345. Reverse Vowels of a String(Easy)
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: “hello”
Output: “holle”
Example 2:
Input: “leetcode”
Output: “leotcede”
Note:
The vowels does not include the letter “y”.
问题分析
两个下标 left,right 分别指向字符串头尾,left 向后移动,直到碰见元音字符,right 向前移动,直到碰见元音字符,交换两元音字符,直到不满足 left<right 时退出。
class Solution {
public:
bool isvowels (char c)
{
char ch[10]={'a','e','i','o','u','A','E','I','O','U'};
for(int i=0;i<10;i++)
if(ch[i]==c)
return true;
return false;
}
string reverseVowels(string s) {
int left=0,right=s.size()-1;
while(left<right)
{
while(!isvowels(s[left])&&left<right)left++;
while(!isvowels(s[right])&&left<right)right--;
swap(s[left],s[right]);
left++;
right--;
}
return s;
}
};
4、判断是不是回文字符串(最多可以删一个字符)
680. Valid Palindrome II(Easy)
Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.
Example 1:
Input: “aba”
Output: True
Example 2:
Input: “abca”
Output: True
Explanation: You could delete the character ‘c’.
Note:
The string will only contain lowercase characters a-z. The maximum length of the string is 50000.
问题分析:
两个指针分别指向头和尾,遇见不相等的字符时,跳过一个字符,判断剩下的是不是回文字符串。
class Solution {
public:
bool validPalindrome(string s) {
int i=0,j=s.size()-1;
while(i<j)
{
if(s[i]!=s[j])
return isPalindrome(s, i+1, j)||isPalindrome(s, i, j-1);
else
{
i++; j--;
}
}
return true;
}
bool isPalindrome(string s,int i,int j)
{
while(i<j)
{
if(s[i++]!=s[j--])
return false;
}
return true;
}
};
5、归并两个有序数组
88. Merge Sorted Array(Easy)
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
问题分析:
将两个有序数组归并,结果放在第一个数组中。
用两个下标分别指向两个数组要归并的尾元素,从尾向头遍历,依次将较大的值放在第一个数组中。
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i=m-1,j=n-1;
int k=m+n-1;
while(i>=0&&j>=0)
{
if(nums1[i]>nums2[j])
nums1[k--]=nums1[i--];
else
nums1[k--]=nums2[j--];
}
while(i>=0)
nums1[k--]=nums1[i--];
while(j>=0)
nums1[k--]=nums2[j--];
}
};
6、判断链表是否存在环
141. Linked List Cycle(Easy)
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Follow up:
Can you solve it using O(1) (i.e. constant) memory?
问题分析:
使用快慢两个指针,快指针每次移动两个节点,慢指针每次移动一个节点,如果存在环,这两个指针一定会相遇。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL)
return false;
ListNode *fast=head;
ListNode *slow=head;
while(fast!=NULL && slow!=NULL && fast->next!=NULL && fast->next->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
return true;
}
return false;
}
};
7、最长子序列
524. Longest Word in Dictionary through Deleting(Medium)
Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
Example 1:
Input:
s = “abpcplea”, d = [“ale”,“apple”,“monkey”,“plea”]
Output:
“apple”
Example 2:
Input:
s = “abpcplea”, d = [“a”,“b”,“c”]
Output:
“a”
Note:
All the strings in the input will only contain lower-case letters.
The size of the dictionary won’t exceed 1,000.
The length of all the strings in the input won’t exceed 1,000.
问题分析:
对于集合中的每个字符串,判断是否可以由指定字符串删除一些字符得到,如果可以,再判断与前面也符合该条件的字符串相比,是否长度更长,如果长度相等,是否字典序更小。
class Solution {
public:
string findLongestWord(string s, vector<string>& d) {
int n=d.size();
string longstr="";
for(int i=0;i<n;i++)
{
if(have(s,d[i]))
{
if(d[i].size()>longstr.size())
longstr=d[i];
else if(d[i].size()==longstr.size()&&d[i]<longstr)
longstr=d[i];
}
}
return longstr;
}
bool have(string s, string target) //判断target能否由s删除而来
{
int i=0, j = 0;
while(i<s.size()&&j<target.size())
{
if (s[i] == target[j])
j++;
i++;
}
if (j == target.size())
return true;
return false;
}
};