zoukankan      html  css  js  c++  java
  • 【leetcode】4. Median of Two Sorted Arrays

    计算中间两个数的平均值

    没被hard难住,这题就是归并排序的应用,注意空指针

    public class Solution {
        public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            int length = length(nums1) + length(nums2);
            boolean isOdd = (length & 1) == 1;
            int left = 0;
            int right = 0;
            
            int middleRight = length / 2;
            int middleLeft = isOdd ? middleRight : middleRight - 1;
            
            int middleLeftValue = 0;
            int middleRightValue = 0;
            
            for (int i = 0; i <= middleRight && i < length; ++i) {
                int leftValue = get(nums1, left);
                int rightValue = get(nums2, right);
                if (leftValue <= rightValue) {
                    left++;
                    if (i == middleLeft) {
                        middleLeftValue = leftValue;
                    }
                    if (i == middleRight) {
                        middleRightValue = leftValue;
                    }
                } else {
                    right++;
                    if (i == middleLeft) {
                        middleLeftValue = rightValue;
                    }
                    if (i == middleRight) {
                        middleRightValue = rightValue;
                    }
                }
            }
            
            return (middleLeftValue + middleRightValue) * 1.0 / 2;
        }
        
        private int length(int[] num) {
            return num == null ? 0 : num.length;
        }
        
        private int get(int[] nums, int index) {
            if (nums == null || index >= nums.length) {
                return Integer.MAX_VALUE;
            } else {
                return nums[index];
            }
        }
    }
  • 相关阅读:
    SQL Server调优系列基础篇
    SQL分组查询及聚集函数的使用
    数据库索引
    ASP.NET MVC5入门指南
    AOP 动态织入的.NET实现
    mmap学习
    Mysql的优化一则
    PHP 5.5 新特性
    19个三维GIS软件对比
    周鸿祎区块链五大缺点, 区块链的100个问题
  • 原文地址:https://www.cnblogs.com/lanhj/p/5373758.html
Copyright © 2011-2022 走看看