1.Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
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.)
暂时把这道题看作是贪心算法的一个应用,因为每次选择的区间范围都是最大的。
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.
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--; } }
未完待续