leetcode刷题
因为现在面临着面试的压力,而且自己的数据结构和算法能力非常差,只能利用leetcode刷刷题来快速提高自己的能力,也记录下自己的刷题策略吧,希望能和大家一起交流下最优解法。
easy题目系列:
1、Two Sum:Given an array of integers, return indices of the two numbers such that they add up to a specific target.
题意:给定整数数组,返回两个数字的索引。这两个数字的和要和目标值相等
我的思路:建立一个int数组用于存储索引值,遍历两次这个数组,第一次从0开始,第二次从1开始,然后只要两个数加起来等于目标值,把数组索引用[ ]取出来,然后返回这个索引值的数组。
代码实现:
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] keys = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
keys[0] = i;
keys[1] = j;
break;
}
}
}
return keys;
}
}
然后查看了别人的优秀代码,大家可以参考下:
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
还有这种用map的,思路也很好,不用事先分配内存空间:
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
2、Reverse Integer:Given a 32-bit signed integer, reverse digits of an integer.
###题意:给定一个32位有符号整数,反转
我的思路:我刚开始用的是下面这个差不多的方法,发现考虑的不全,然后参考了别人的代码,是我目前比较能理解的一种解题方法。(好惭愧)
代码实现:
class Solution {
public int reverse(int x) {
int res = 0;
while(x != 0){
int temp = res * 10 + x % 10;
x = x / 10;
if(temp / 10 != res){
res = 0;
break;
}
res = temp;
}
return res;
}
}
优秀代码:
class Solution {
public:
int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
};
还有这种的,我这个小白有点看不懂:
class Solution {
public int reverse(int x) {
List list = new LinkedList();
while (x != 0) {
int i = x % 10;
list.add(Long.valueOf(i));
x = x / 10;
}
int n = list.size();
long y = 0;
for (int i = n; i > 0; i--) {
y += Math.pow(10, i-1) * (long) list.get(n-i);
}
if (y < Integer.MIN_VALUE || y > Integer.MAX_VALUE) {
return 0;
}
return (int) y;
}
}
Integer.MAX_VALUE+1=Integer.MIN_VALUE,这个跟原码、反码、补码有关,大家可以补下这个方面知识。
今天先分享两个题目,欢迎大家留言交流。