Question :101 - 200
# Question :101 - 200
# Q122*: 买卖股票的最佳时机 II (opens new window)
public static int maxProfit(int[] prices) {
int profit = 0;
for (int i = 1; i < prices.length; ++i) {
profit += Math.max(0, prices[i] - prices[i - 1]);
}
return profit;
}
# Q125: 验证回文串 (opens new window)
public boolean isPalindrome(String s) {
if(s.isEmpty()) {
return true;
}
char[] charArray = s.toCharArray();
int i = 0, y = charArray.length - 1;
while ( i < y){
char c1 = validateChar(charArray[i]);
if(c1 == 0) {
++i;
continue;
}
char c2 = validateChar(charArray[y]);
if(c2 == 0) {
--y;
continue;
}
if(c1 != c2) {
return false;
}
++i;
--y;
}
return true;
}
private char validateChar(char ch) {
if(ch >= 'A' && ch <= 'Z') {
return (char)(ch+'a'-'A');
}else if((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <='9')) {
return ch;
}else {
return 0;
}
}
# Q136: 只出现一次的数字 (opens new window)
public static int singleNumber(int[] nums) {
int n = nums[0];
for (int i = 1; i < nums.length; ++i) {
n = n ^ nums[i];
}
return n;
}
# Q189*: 轮转数组 (opens new window)
public void rotate(int[] nums, int k) {
int n = nums.length;
k %= n;
reverse(nums, 0, n - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, n - 1);
}
private void reverse(int[] arr,int start,int end) {
while(start < end) {
int temp = arr[start];
arr[start++] = arr[end];
arr[end--] = temp;
}
}
上次更新: 5/21/2023, 11:34:33 PM