TwoSum这题就直接把数字和位置放进Map里,然后用TARGET减当前的数,用结果去Map里找就行。不算是好的解法。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i< nums.length; i++) {
if (map.containsKey(target - nums[i])) {
result[0] = map.get(target - nums[i]);
result[1] = i;
}
map.put(nums[i], i);
}
return result;
}
}
image.png
数字回文这道题,之前是做过类似的,拿链表测字符串回文的,这次要做的是不依赖成字符串和链表来检测数字的回文。也比较简单。
class Solution {
public static boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
if (x <10) {
return true;
}
int leftPointer = 0;
int rightPointer = 0;
int remainder = x;
while (remainder >= 10) {
remainder = remainder / 10;
rightPointer++;
}
while (leftPointer < rightPointer) {
int leftDigit = getLeftDigit(x, rightPointer, leftPointer);
int rightDigit = getRightDigit(x);
if (leftDigit != rightDigit) {
return false;
}
x = removeFirstAndLastDigit(x, rightPointer, leftPointer);
leftPointer++;
rightPointer--;
}
return true;
}
private static int removeFirstAndLastDigit(int x, int rightPointer, int leftPointer) {
return x % (int)Math.pow(10, rightPointer - leftPointer) / 10;
}
private static int getLeftDigit(int x, int rightPointer, int leftPointer) {
return x / (int)Math.pow(10, getCurrentLength(rightPointer, leftPointer));
}
private static int getRightDigit(int x) {
return x % 10;
}
private static int getCurrentLength(int right, int left) {
return right - left;
}
}
网友评论