一、两数之和
给定一个整数数组 nums和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那两个整数,并返回它们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。 你可以按任意顺序返回答案。 来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/two-sum
方法一:暴力求解法
两个for循环,遍历该数组中的每一个数
/**
* 暴力求解法
*/
public static int[] twoSum(int[] nums, int target) {
int[] array = new int[2];
c:
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
array[0] = i;
array[1] = j;
break c;
}
}
}
return array;
}
方法二:哈希表求解法(推荐)
/**
* 哈希表求解法
* 思路:
* 1. 创建一个哈希表
* 2. 将数组中的值作为key,下标作为value放入哈希表
* 3. 从数组的第二个元素开始遍历
* 4. 使用map.containsKey(int key)来判断之前存入的key中是否有符合条件的元素
* 5. 将符合条件的元素的下标存入新的数组,若找不到则抛出异常
*/
public static int[] twoSum01(int[] nums, int target) {
int len = nums.length;
Map<Integer, Integer> map = new HashMap<>(len - 1);
map.put(nums[0], 0);
for (int i = 1; i < len; i++) {
int another = target - nums[i];
if (map.containsKey(another)) {
return new int[]{i, map.get(another)};
} else {
map.put(nums[i], i);
}
}
throw new IllegalArgumentException("NO TWO SUM SOLUTION");
}
二、判断是否为回文数
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。 回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 例如,121 是回文,而 123 不是。 来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/palindrome-number
方法一:字符串反转法
/**
* 反转字符串法
* 思路:
* 1. 将int类型的数字转换为字符串
* 2. 调用reverse()方法反转字符串
* 3. 再与之前的字符串比较
*/
public static boolean isPalindromic(int num) {
if (num < 0) {
return false;
} else {
Integer integer = new Integer(num);
String str = integer.toString();
StringBuilder sb = new StringBuilder(str);
sb.reverse();
if (str.equals(sb.toString())) {
return true;
} else {
return false;
}
}
}
方法二:反转一半数字法(推荐)
/**
* 反转一半数字法
* 思路:
* 1. 创建一个整型变量
* 2. 反转一半的数字,并赋值给该变量
* 3. 当临时变量大于x时,终止循环
*/
public static boolean isPalindromicPlus(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) {
return false;
} else {
int temp = 0;
while (x > temp) {
temp = temp * 10 + x % 10;
x = x / 10;
}
if (temp / 10 == x || temp == x) {
return true;
}
}
return false;
}