1.Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
1. 找到最大位数, 比如321 是百位数, 1221是千位
2. 每次比较最高和最低位数
bool isPalindrome(int x) {
if(x<0) return false;
if(x == 0) return true;
int div = 1;
while(x/div>=10){
div *=10;
}
while(x>0){
int r = x%10;
int l = x/div;
if(l!= r) return false;
x = (x%div)/10;
div/=100;
}
return true;
}
2. Jump Game II
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2
. (Jump 1
step from index 0 to 1, then 3
steps to the last index.)
从左往右扫描,维护一个覆盖区间,每扫过一个元素,就重新计算覆盖区间的边界。比如,开始时区间[start, end], 遍历A数组的过程中,不断计算A[i]+i最大值(即从i坐标开始最大的覆盖坐标),并设置这个最大覆盖坐标为新的end边界。而新的start边界则为原end+1。不断循环,直到end> n.
暂时把这道题看作是贪心算法的一个应用,因为每次选择的区间范围都是最大的。
int jump(int A[], int n) {
int start = 0;
int end = 0;
int count = 0;
if(n==1) return 0;
while(end<n){
int max = 0;
count++;
for(int i = start; i<=end;i++){
if(A[i]+i >= n-1){
return count;
}
if(A[i]+i > max){
max = A[i]+i;
}
}
start = end+1;
end = max;
}
}
3.
Next Permutation
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3
→ 1,3,2
3,2,1
→ 1,2,3
1,1,5
→ 1,5,1
void nextPermutation(vector<int> &num) {
int vioIndex = num.size()-1;
while(vioIndex >0){
if(num[vioIndex]>num[vioIndex-1])
break;
vioIndex--;
}
if(vioIndex>0){
vioIndex--;
int rightIndex = num.size()-1;
while(rightIndex>=0 && num[rightIndex]<=num[vioIndex]){
rightIndex--;
}
int swap = num[vioIndex];
num[vioIndex] = num[rightIndex];
num[rightIndex] = swap;
vioIndex++;
}
int end = num.size()-1;
while(end>vioIndex){
int swap = num[vioIndex];
num[vioIndex] = num[end];
num[end] = swap;
vioIndex++;
end--;
}
}
4.
未完待续