leetcode学习总结

转自https://leetcode-cn.com/

1.两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

class Solution {
    public static int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        for(int i = 0;i<nums.length;i++){
            for(int j = i+1;j<nums.length;j++){
                int a = nums[i] + nums[j];
                if(target == a){
                  res[0] = i;
                  res[1] = j;
                  break;
return res; } } }
return res; } public static void main(String[] args){ int[] nums = {0,1,2,3,4,5,6}; int target = 4; int[] rest = Solution.twoSum(nums,target); } }

 2.整数反转

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231,  231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

class Solution {
    public int reverse(int x) {
        long temp = 0;
       
        while(x != 0){
            int pop = x % 10;
            temp = temp * 10 + pop;
            
            if(temp > Integer.MAX_VALUE || temp < Integer.MIN_VALUE){
                return 0;
            }
            x /= 10;
        }
        return (int)temp;
    }
}

猜你喜欢

转载自www.cnblogs.com/wwmiert/p/11026680.html