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

来源:互联网 发布:pdf.js 打开 word文档 编辑:程序博客网 时间:2024/06/17 09:24

<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

Answer:

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: 123Output:  321

Example 2:

Input: -123Output: -321

Example 3:

Input: 120Output: 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.

Answer:
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型也传不进来。