<Java算法实现--LeetCode(4)(7)>2017-11-22

<1>问题描述

SOURCE : LeetCode(4)

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example2 :

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

A nsw er:

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int m = nums1.length;
        int n = nums2.length;
        int k = m + n;
        int[] result = new int[k];
        int i = 0, j = 0, q = 0;
        while(i < m && j < n){
            if(nums1[i] < nums2[j])
                result[q++] = nums1[i++];
            else
                result[q++] = nums2[j++];
        }
        
        while(i < m)
            result[q++] = nums1[i++];
        while(j < n)
            result[q++] = nums2[j++];
        
        double median = 0;
        if(k%2 == 0)
            median = (double)(result[k/2]+result[k/2 - 1])/2;
        else
            median = result[k/2];
        return median;
    }
}
这道题吧,说难不难,但是却挺有意思的,求中位数,这里可以引出一个话题,如何判断一个数组是有序的?

另外最后结果保留小数需要强转,各位注意,我就忘了,半天得到错误的结果,愚蠢。

 

<2>问题描述

SOURCE : LeetCode(7)

Given a 32-bit signed integer, reverse digits of an integer.


Example 1:

Input: 123
Output:  321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

A nsw er:
class Solution {
    public int reverse(int x) {
        int result = 0;
        // if(x>2^31 || x<(-2^31))
        //     return 0;
        while(x != 0){
            int lastNum = x%10;
            int temp = result*10+lastNum;
            if(result != (temp-lastNum)/10)
                return 0;
            result = temp;
            x = x/10;
        }
        return result;
    }
}
关键int型吧,x是int型,但是反转后,就可能超出范围了,超出int型范围的值仍然是有的,只不过是多出的,正负都会变化,所以要验证一下得到的结果再倒着算能不能一样,不一样那就是超范围了,直接返回0就可以了,开头却无需判断,毕竟不是int型也传不进来。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值