2021-07-02算法题

95 阅读1分钟

1.两数之和 image.png 思路:双层循环暴力搜索。由于最后结果只有两个整数,所以当等于target时直接return即可,不会出现重复的情况,

class Solution {
    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[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[]{};
    }
}
  1. 整数反转(*) image.png 思路:
  • n不断乘以10并加上余数,x则不断除以10
  • 使用long来辅助判断溢出
  • 需要考虑负数和int溢出的问题
class Solution {
    public int reverse(int x) {
        long n = 0;
        while (x != 0) {
            n = n * 10 + x % 10;
            x /= 10;
        }
        if (n > 2147483647 || n < -2147483648) {
            return 0;
        } else {
            return (int)n;
        }
    }
}
  1. 回文数 image.png 思路:负数直接return false,整数先反转再判断
class Solution {
    public long reverse(int x) {
        long n = 0;
        while (x != 0) {
            n = n * 10 + x % 10;
            x /= 10;
        }
        return n;
    }
    public boolean isPalindrome(int x) {
        if (x < 0) {
            return false;
        } else {
            if (reverse(x) == x) {
                return true;
            } else {
                return false;
            }
        }
    }
}