Interview Questions: Quicksort

Interview Questions: Minimum Spanning Trees Minimum Spanning Trees Bottleneck minimum spanning tree. Given a connected edge-weighted graph, design an efficient algorithm to find a minimum bottleneck spanning tree. The bottleneck capacity of a ... 阅读详情

Quicksort

Nuts and bolts. A disorganized carpenter has a mixed pile of n nuts and n bolts. The goal is to find the corresponding pairs of nuts and bolts. Each nut fits exactly one bolt and each bolt fits exactly one nut. By fitting a nut and a bolt together, the carpenter can see which one is bigger (but the carpenter cannot compare two nuts or two bolts directly). Design an algorithm for the problem that uses at most proportional to nlogn compares (probabilistically).

无法通过nuts之间/bolts之间比较来区分各自大小,只能通过一个nut和一个bolt的比较来区分大小。使用快排时,从nuts[]中选出一个nut作为比较基准来对bolts[]进行分块,记分块的结果为m。再以bolts[m]为比较基准对nuts[]进行分块,其结果同样为m。递归排序左右两块。当两个数组都排好序后,即完成了配对。

import java.util.Random;

class NB {
    int size;

    public NB(int size) {
        this.size = size;
    }
}

class Nut extends NB {
    public Nut(int size) {
        super(size);
    }
}

class Bolt extends NB {
    public Bolt(int size) {
        super(size);
    }
}

public class NutsAndBolts {
    private Nut[] nuts;
    private Bolt[] bolts;

    public NutsAndBolts(Nut[] nuts, Bolt[] bolts) {
        this.nuts = nuts;
        this.bolts = bolts;
        sort(0, nuts.length - 1);
    }

    private void sort(int left, int right) {
        if (left >= right) {
            return;
        }
        int random = new Random().nextInt(right - left + 1) + left;
        swap(nuts, left, random);
        for (int i = left; i <= right; i++) {
            if (bolts[i].size == nuts[left].size) {
                swap(bolts, left, i);
                break;
            }
        }
        int m = partition(bolts, nuts[left], left, right);
        partition(nuts, bolts[m], left, right);
        sort(left, m - 1);
        sort(m + 1, right);
    }

    // 加入base是因为题目规定同类型之间无法比较,只能不同类型间比较
    // base为待分块数组的相对应数组中的元素
    private int partition(NB[] a, NB base, int left, int right) {
        NB temp = a[left];
        while (left < right) {
            while (left < right && a[right].size > base.size) {
                right--;
            }
            a[left] = a[right];
            while (left < right && a[left].size <= base.size) {
                left++;
            }
            a[right] = a[left];
        }
        a[left] = temp;
        return left;
    }

    private void swap(NB[] a, int i, int j) {
        NB temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}

Selection in two sorted arrays. Given two sorted arrays a*[] and b[], of sizes n 1 n_1 n1​ and n 2 n_2 n2​, respectively, design an algorithm to find the k t h k^{th} kth largest key. The order of growth of the worst case running time of your algorithm should be logn, where n = n 1 + n 2 n = n_1 + n_2 n=n1​+n2​.

  • Version 1: n 1 = n 2 n_1 = n_2 n1​=n2​ and k=n/2
  • Version 2: k=n/2
  • Version 3: no restrictions

LeetCode原题:4. Median of Two Sorted Arrays (H)

public class SelectionInTwo {
    public static int findKth(int[] a, int[] b, int k) {
        return findKth(a, b, 0, a.length - 1, 0, b.length - 1, k);
    }

    private static int findKth(int[] a, int[] b, int as, int ae, int bs, int be, int k) {
        int aLen = ae - as + 1;
        int bLen = be - bs + 1;

        // 边界条件处理

        // 保持a为长度较小的数组
        if (aLen > bLen) {
            return findKth(b, a, bs, be, as, ae, k);
        }
        // a被删完后可直接找到第k大
        if (aLen == 0) {
            return b[k - 1];
        }
        // k==1为特殊情况
        if (k == 1) {
            return Math.min(a[as], b[bs]);
        }

        int p = Math.min(aLen, k / 2);
        int q = k - p;
        if (a[as + p - 1] < b[bs + q - 1]) {
            return findKth(a, b, as + p, ae, bs, be, k - p);
        } else if (a[as + p - 1] > b[bs + q - 1]) {
            return findKth(a, b, as, ae, bs + q, be, k - q);
        } else {
            return a[as + p - 1];
        }
    }
}

Decimal dominants. Given an array with n keys, design an algorithm to find all values that occur more than n/10 times. The expected running time of your algorithm should be linear.

在包含n个元素的数组中找出所有出现次数大于n/10的元素,要求复杂度为O(N)。

最简单的方法为hash,但是空间复杂度高达O(N)。

根据hint优化方法:如果将数组排好序,那么每个出现次数大于n/10的元素最多只可能为 a [ ( n 10 + 1 ) ∗ i − 1 ] a[(\frac{n}{10}+1)*i-1] a[(10n​+1)∗i−1]中的9个。针对这几个分隔节点上的元素去hash可以大大减少额外空间。寻找第K大可以使用quick-select方法。

import java.util.HashSet;
import java.util.Set;

public class DecimalDominants {
    private int[] a;
    private Set<Integer> possible;
    private int[] count;
    private final int MIN;

    public DecimalDominants(int[] a) {
        this.a = a;
        MIN = a.length / 10 + 1;
        possible = new HashSet<>();
        count = new int[9];
        run();
    }

    public void run() {
        for (int i = 1; i <= 9; i++) {
            int k = MIN * i;
            if (k > a.length) {
                break;
            }
            possible.add(findKth(k));
        }

        // possible.size()最大为9
        for (Integer p : possible) {
            int count = 0;
            for (int i = 0; i < a.length; i++) {
                if (a[i] == p) {
                    count++;
                    if (count == MIN) {
                        System.out.println(p);
                        break;
                    }
                }
            }
        }
    }

    private int findKth(int k) {
        int left = 0;
        int right = a.length - 1;
        while (left < right) {
            int m = partition(left, right);
            if (m < k - 1) {
                left = m + 1;
            } else if (m > k - 1) {
                right = m - 1;
            } else {
                return a[k - 1];
            }
        }
        return a[k - 1];
    }

    private int partition(int left, int right) {
        int temp = a[left];
        while (left < right) {
            while (left < right && a[right] > temp) {
                right--;
            }
            a[left] = a[right];
            while (left < right && a[left] <= temp) {
                left++;
            }
            a[right] = a[left];
        }
        a[left] = temp;
        return left;
    }
}

参考

啊h_a - 普林斯顿大学算法课:Nuts and bolts

什么是OAuth 2.0? OAuth2.0是一种授权协议而非登录协议,核心思想是通过令牌(Token)而非密码实现安全授权。它涉及三个关键角色:用户、第三方应用和身份提供商(IdP)。最常用的授权码流程(AuthorizationCode Flow)通过浏览器三方对话,确保用户密码只提供给IdP而非第三方应用。OAuth2.0提供四种授权方式,其中授权码和客户端凭证是当前主流,而隐式和密码模式已不推荐。需要注意的是,OAuth2.0解决的是授权问题,身份认证需通过OpenID Connect实现。该协议通过临时令牌机制,实现了&qu 阅读详情

相关推荐

R3LIVE 1.0 适配 Velodyne 16线雷达:3步配置解决150米漂移问题

本文详细解析了R3LIVE 1.0适配Velodyne 16线雷达时出现的150米漂移问题,并提供三步配置方案。通过调整雷达类型设置、运动补偿与时间对齐、视觉-激光联合优化等关键参数,有效解决了系统漂移问题,提升定位精度。适用于机器人定位与建图领域的开发者。

weixin_29054195的博客 268

Coursera Algorithms week3 快速排序 练习测验: Decimal dominants(寻找出现次数大于n/10的元素)...

题目原文: Decimal dominants.Given an array withn keys, design an algorithm to find all values that occur more than n/10times. The expected running time of your algorithm should be linear. 分析: 直观上将n...

weixin_30294295的博客 261

高通camera:PDAF的配置与测试

确认相关log日志都已经打开了之后,判断是在3A算法中没有应用到PDAF,可能是之前在调试AF效果的时候关闭了PDAF,打开效果文件对应的文件夹,在\kamorta_lce_S5K3P9\Scenario.Default\XML\STATS。在log中搜索af_pdaf_proc_pd_single,这个函数是pdaf算法中的,源码被封装了,这里看不到,因此只能通过log打印出来的参数来分析pd是否正确,主要参数有pd ,defocus,confidence。PDAF的配置与测试。

arvin_xiong的博客 2486

PowerDesigner概念设计模型(CDM)中的3种实体关系

CDM是大多数开发者使用PD时最先创建的模型,也是整个数据库设计最高层的抽象。CDM是建立在传统的ER图模型理论之上的,ER图中有三大主要元素: 实体型,属性和联系。其中实体型对应到CDM中的Entity,属性对应到CDM中每个Entity的Attribute,在概念上基本上是一一对应的。 但在联系上,CDM有了比较大的扩展,除了保留ER图原有的RelationShip概念之外,还增加了Assoc...

海边夕阳 1439

DNF单机版搭建全攻略:从零开始到局域网联机(含常见问题解决)

本文提供详细的DNF单机版搭建指南,从环境配置到局域网联机设置,涵盖服务端安装、数据库配置及常见问题解决方案。适合新手和有经验的玩家,帮助快速搭建专属游戏服务器,重温经典游戏体验。

weixin_30832143的博客 846

从GEFCom到UCI:手把手教你构建电力负荷时空预测模型(Python版)

本文详细介绍了如何从GEFCom到UCI数据集构建电力负荷时空预测模型(Python版),涵盖数据集解析、时空特征工程、模型架构设计及工业部署优化。通过多任务图神经网络(MTGNN)实现高精度预测,并结合边缘计算和在线学习机制提升实际应用效果,为能源管理系统提供可靠解决方案。

lambda的博客 812

InterviewQuestion-QuickSort

1。Nuts and bolts. A disorganized carpenter has a mixed pile of n nuts and n bolts. The goal is to find the corresponding pairs of nuts and bolts. Each nut fits exactly one bolt and each bolt fits exact

sun%moon 388

网络虚拟化介绍(OVS、DVS)

网络虚拟化概念网络虚拟化就是把网络层的一些功能从硬件中剥离出来,建立新的网络虚拟层;该虚拟层可以接管网络服务和配置,实现网络服务与物理层的解耦,打破物理资源限制;通过网络虚拟层能够在一个物理网络上模拟出多个逻辑网络,并且多用户在逻辑网络上相互隔离,保证网络安全网络虚拟化的特点隔离性:不同租户的流量相互之间不能互访;但是IP/MAC地址都可以独立规划可移动性:虚拟机可以跨二层/三层迁移,甚至可以跨广域网迁移(迁移前后虚拟机Vlan和IP地址都不会发生变化)可扩展性:逻辑网络的规模和数量可扩展。

m0_49864110的博客 1万+

Interview-quicksort

Nuts and bolts. Selection in two sorted arrays.

zerods-seu的博客 1198

手把手教你用STM32CubeMX配置WS2812的PWM+DMA驱动(附完整代码)

本文详细介绍了如何使用STM32CubeMX配置PWM+DMA驱动WS2812全彩灯带,包括硬件选型、STM32F103C8T6的时钟配置、定时器与PWM设置、DMA传输优化等关键步骤,并提供了完整的代码实现和常见问题解决方案,帮助开发者高效控制WS2812灯带。

weixin_30859423的博客 440

TC3XX - MCAL知识点(三十三):基于EB Tresos配置Tc3xx的MCAL代码如何产生中心对称的三相六路发波波形

本文用于记录如何在英飞凌 tc3xx 芯片的应用开发中,借助 EB Tresos 配置工具生成的配置代码与 MCAL 源码相结合,进而实现三相六路中心对称互补的 PWM 输出效果。外部资源需求:EB Tresos23.0以上、Tasking\Hightec编译器、示波器\逻辑分析仪。

梦想技术家 1210

Coursera - Algorithm (Princeton) - 习题与解答 - Week 3

Week 3 Merging with smaller auxiliary array 原题 Suppose that the subarray a[0]\mathtt{a[0]}a[0] to a[n−1]\mathtt{a[n-1]}a[n−1] is sorted and the subarray a[n]\mathtt{a[n]}a[n] to a[2∗n−1]\mathtt{a[2*n-...

支锦铭的博客 551

Idea插件Plugins无法联网下载 解决方法(终极版必解决!)

插件联网的Bug疑难杂症,网络上不一样的解决方式以及独特的彩蛋!包解决

码农研究僧的博客 5515

Google interview question: selection questions

上一遍文章总结了用quickSort思想解决的问题,那么面试题中自然少不了和selection algorithm相关的题目。 Selection algorithm能在时间复杂度O(N)寻找一个数组中第K大/小的元素,也就是将数组划分成比第K元素大和比第K元素小两部分。对基本的selection algorithm,leetcode有对应的原题可以练习。 https://leetcode.c...

weixin_30405421的博客 138

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

SwiftNIO NIOHTTP1Server:官方 HTTP 服务器示例的启动方式、端点实现与源码级剖析

`NIOHTTP1Server` 是 SwiftNIO 仓库内置的官方示例可执行程序,它用 `NIOHTTP1` + `NIOPosix` 构建了一个功能完整的 HTTP/1.1 服务器:支持 TCP、Unix Domain Socket 乃至标准输入/输出三种绑定方式,覆盖 `sendfile` 零拷贝发文件、非阻塞分块读文件、chunked 流式响应、trailers、keep-alive 与

gitblog_00077的博客 154

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

8 Puzzle

8 Puzzle Board.java 照着API写即可。注意每次调用twin()都要返回相同的值,即twin()只能交换两个固定位置的数字。 import edu.princeton.cs.algs4.StdRandom; import java.util.ArrayList; import java.util.List; public class Board { private f...

Mapoos 900

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

Collinear Points

Collinear Points Point.java 照要求补API即可。 import java.util.Comparator; import edu.princeton.cs.algs4.StdDraw; public class Point implements Comparable<Point> { private final int x; // x-c...

Mapoos 717

Percolation

Percolation Percolation.java 主要问题为backwash。其形成原因为:因为存在上下两个虚拟节点,当percolates()为true上下贯通时,所有在最底排的已经打开的节点都会变成与上虚拟节点连通(每打开一个底部节点,都会将其与下虚拟节点连通)。解决方法是再设置一个union-find,但只提供上虚拟节点,将isFull()放在第二个union-find中进行判断。 ...

Mapoos 685

Interview Questions: Stacks and Queues

Interview Questions: Stacks and Queues Queue with two stacks. Implement a queue with two stacks so that each queue operations takes a constant amortized number of stack operations. 利用两个栈来实现队列,具体方法为:...

Mapoos 461

Interview Questions: Analysis of Algorithms

Analysis of Algorithms 3-SUM in quadratic time. Design an algorithm for the 3-SUM problem that takes time proportional to n2n^2n2 in the worst case. You may assume that you can sort the n integers in...

Mapoos 452

Interview Questions: Balanced Search Trees

Balanced Search Trees Red–black BST with no extra memory. Describe how to save the memory for storing the color information when implementing a red–black BST. Hint: modify the structure of the BST to...

Mapoos 392

Interview Questions: Union-Find

Interview Questions: Union-Find Social network connectivity. Given a social network containing nn members and a log file containing mm timestamps at which times pairs of members formed friendships, d...

Mapoos 318

Deques and Randomized Queues

Deques and Randomized Queues Deque.java 双向队列,因为要求所有操作的复杂度为O(1)O(1)O(1),采用双向链表进行实现。 import java.util.Iterator; import java.util.NoSuchElementException; public class Deque<Item> implements Iterab...

Mapoos 313

Interview Questions: Priority Queues

Priority Queues Dynamic median. Design a data type that supports insert in logarithmic time, find-the-median in constant time, and remove-the-median in logarithmic time. If the number of keys in the ...

Mapoos 290

Interview Questions: Elementary Symbol Tables

Elementary Symbol Tables Java autoboxing and equals(). Consider two

Mapoos 283

Interview Questions: Hash Tables

Hash Tables 4-SUM. Given an array a[] of nn integers, the 4-SUM problem is to determine if there exist distinct indices i, j, k, and l such that a[i]+a[j]=a[k]+a[l]. Design an algorithm for the 4-SUM...

Mapoos 281
上一篇: Collinear Points
下一篇: 8. String to Integer (atoi) (M)
绿色小光头
博客等级 码龄10年 10粉丝 301原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值