leetcode算法题解(Java版)-14-第k小数问题

简介: 题目要求在O(log(m+n))时间内完成,可以转换为找到假设两个数组合并后的第(m+n)/2小的数。

一、第k小数问题

题目描述

There are two sorted arrays A and B 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)).

思路

  • 题目要求在O(log(m+n))时间内完成,可以转换为找到假设两个数组合并后的第(m+n)/2小的数。
  • 这里先忽略奇偶问题,具体实现代码中会有不同。先假设A和B中的数都大于k/2,比较A[k/2-1]和B[k/2-1](减1是因为数组下标从零开始)如果A[k/2-1]

代码

public class Solution {
    public double findMedianSortedArrays(int A[], int B[]) {
        //奇偶数不会有影响,最后中位数就是平均值
        int m = A.length,n = B.length;
        int l = (m+n+1)/2;
        int r = (m+n+2)/2;
        
        return (findKthNum(A,B,0,0,l)+findKthNum(A,B,0,0,r))/2.0;
    }
    private double findKthNum(int [] A,int [] B,int Astart,int Bstart,int k){
        int lenA = A.length;
        int lenB = B.length;
        if(Astart>=lenA){
            return B[Bstart+k-1];
        }
        if(Bstart>=lenB){
            return A[Astart+k-1];
        }
        if(k==1){
            return Math.min(A[Astart],B[Bstart]);
        }
        int minA = Integer.MAX_VALUE;
        int minB = Integer.MAX_VALUE;
        if(Astart+k/2-1<A.length){
            //如果这里超过了A数组的范围,那就说明A中有将A、B合并后一半以上的
            //数,也就是说中位数肯定在A中。那后面的minB<minA(MAX_VALUE),就会成立,从而舍弃B中的前一些无关的数
            minA = A[Astart+k/2-1];
        }
        if(Bstart+k/2-1<B.length){
            minB = B[Bstart+k/2-1];
        }
        if(minA<minB){
            return findKthNum(A,B,Astart+k/2,Bstart,k-k/2);
        }
        else{
            return findKthNum(A,B,Astart,Bstart+k/2,k-k/2);
        }
    }
}

二、map映射

题目描述

Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

思路

  • 给一列数,给一个目标值,找出数列中两个数和为这个值的下标。因为数没有排序,可以考虑用map来构建数值和下标的映射,更狠一点,在遍历数组的同时,用map构建目标值减去当前这个数的值与当前下标的映射,然后对每一个遍历到的数判断是否已存在在map中。

代码

import java.util.HashMap;

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int n = numbers.length;
        int [] res = new int [2];
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i=0 ;i<n;i++){
            if(map.containsKey(numbers[i])){
                res[0]=map.get(numbers[i])+1;
                res[1]=i+1;
                break;
            }
            else{
                map.put(target-numbers[i],i);
            }
        }
        return res;
    }
}

三、动态规划

题目描述

You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

思路

  • 题目提示了用动态规划来解,那自然想到从step 1,2,3,.。于是慢慢推了看看,看是否能得到状态转移方程。写了几个,发现:dp[i]=dp[i-1]+dp[i-2];

代码

public class Solution {
    public int climbStairs(int n) {
        int [] dp = new int[n+2];
        dp[1]=1;
        dp[2]=2;
        for(int i=3;i<=n;i++){
            dp[i]=dp[i-1]+dp[i-2];
        }
        return dp[n];
    }
}

//优化一下空间复杂度
public class Solution {
    public int climbStairs(int n) {
        if(n<=2){
            return n;
        }
        int one_step_before=2;
        int two_step_before=1;
        for(int i=3;i<=n;i++){
            int cur = one_step_before+two_step_before;
            two_step_before = one_step_before;
            one_step_before = cur;
        }
        return one_step_before;
    }
}
目录
相关文章
|
30天前
|
存储 算法 JavaScript
怎么刷算法,leetcode上有哪些经典题目
怎么刷算法,leetcode上有哪些经典题目
15 0
|
8天前
|
算法 Java C语言
C++和Java中的随机函数你玩明白了吗?内附LeetCode470.rand7()爆改rand10()巨详细题解,带你打败LeetCode%99选手
C++和Java中的随机函数你玩明白了吗?内附LeetCode470.rand7()爆改rand10()巨详细题解,带你打败LeetCode%99选手
|
23天前
|
存储 算法 Java
Java数据结构与算法-java数据结构与算法(二)
Java数据结构与算法-java数据结构与算法
66 1
|
2天前
|
算法 DataX
二叉树(中)+Leetcode每日一题——“数据结构与算法”“剑指Offer55-I. 二叉树的深度”“100.相同的树”“965.单值二叉树”
二叉树(中)+Leetcode每日一题——“数据结构与算法”“剑指Offer55-I. 二叉树的深度”“100.相同的树”“965.单值二叉树”
|
10天前
|
算法 安全 Java
java代码 实现AES_CMAC 算法测试
该代码实现了一个AES-CMAC算法的简单测试,使用Bouncy Castle作为安全提供者。静态变量K定义了固定密钥。`Aes_Cmac`函数接受密钥和消息,返回AES-CMAC生成的MAC值。在`main`方法中,程序对给定的消息进行AES-CMAC加密,然后模拟接收ECU的加密结果并进行比较。如果两者匹配,输出&quot;验证成功&quot;,否则输出&quot;验证失败&quot;。辅助方法包括将字节转为16进制字符串和将16进制字符串转为字节。
|
17天前
|
搜索推荐 Java
Java排序算法
Java排序算法
18 0
|
17天前
|
搜索推荐 Java
Java基础(快速排序算法)
Java基础(快速排序算法)
23 4
|
20天前
|
存储 算法 JavaScript
Java入门高频考查算法逻辑基础知识3-编程篇(超详细18题1.8万字参考编程实现)
解决这类问题时,建议采取下面的步骤: 理解数学原理:确保你懂得基本的数学公式和法则,这对于制定解决方案至关重要。 优化算法:了解时间复杂度和空间复杂度,并寻找优化的机会。特别注意避免不必要的重复计算。 代码实践:多编写实践代码,并确保你的代码是高效、清晰且稳健的。 错误检查和测试:要为你的代码编写测试案例,测试标准的、边缘情况以及异常输入。 进行复杂问题简化:面对复杂的问题时,先尝试简化问题,然后逐步分析和解决。 沟通和解释:在编写代码的时候清晰地沟通你的思路,不仅要写出正确的代码,还要能向面试官解释你的
32 0
|
23天前
|
XML 存储 算法
Java数据结构与算法-java数据结构与算法(五)
Java数据结构与算法-java数据结构与算法
47 0
|
1月前
|
算法 搜索推荐 Java
利用java编写的项目设备调配系统代码示例(内含5种设备调配的算法)
利用java编写的项目设备调配系统代码示例(内含5种设备调配的算法)
13 1