算法入門篇八 貪心算法

牛客網?左程云老師的算法入門課

貪心算法

貪心算法的解題步驟?

例子?

題目要求

?解題策略

  • 按照結束時間早的會議先安排,比如先安排【2,4】,當4結束了,所有開始時間小于4的全部淘汰,【1,7】、【3,4】,【2,8】,將【5,6】加入安排,將【7,10】加入安排

?代碼?

// package class07;import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;public class Code04_BestArrange {public static class Program {public int start;public int end;public Program(int start, int end) {this.start = start;this.end = end;}}public static class ProgramComparator implements Comparator<Program> {@Overridepublic int compare(Program o1, Program o2) {return o1.end - o2.end;}}public static int bestArrange(Program[] programs, int timePoint) {Arrays.sort(programs, new ProgramComparator());int result = 0;// 從左往右依次遍歷所有的會議for (int i = 0; i < programs.length; i++) {if (timePoint <= programs[i].start) {result++;timePoint = programs[i].end;}}return result;}//使用暴力解法public static int bestArrangeForce(Program[] programs,int timePoint){HashSet<Program> set = new HasgSet<>(Arrays.asList(programs));}//會議的集合是set,當前時間是timePoint//返回集合中最多可以安排幾個項目public static int process(HashSet<Program>set ,int timepoint){HashSet<Program> candidates = new HashSet<>();for(Program program : set){if(program.start >= timepoint){candidates.add(program);}}//tmp只是為了使用迭代器HashSet<Program> tmp = new HashSet<>(candidates);int result = 0;//嘗試將每一個項目,作為第一個安排的項目for(Program program : tmp){candidates.remove(program);int next = process(candidates, program.end);result = Math.max(result,next+1);candidates.add(program);}return result;}public static void main(String[] args) {}}
  • 注意事項:對于HashSet集合中的元素,不可以一邊遍歷一邊刪除。需要使用一個tmp集合,將滿足條件條件的元素放到tmp中,然后遍歷tmp集合,刪除原有的集合中的元素
  • 例子:將1到8元素放入到集合set中,需要刪除集合中小于5的元素,所以遍歷set集合,將小于5的元素收集到tmp集合中,然后遍歷tmp集合,刪除set集合中小于5的元素,最后遍歷打印set集合。

代碼

 HashSet<Integer> set = new HashSet<>();set.add(1);set.add(2);set.add(3);set.add(4);set.add(5);set.add(6);set.add(7);set.add(8);HashSet<Integer> tmp = new HashSet<>();//刪除集合中比5小的數//不可以一邊遍歷一邊刪除元素for(Integer i : set){if(i < 5){tmp.add(i);}}for(Integer i : tmp){set.remove(i);}for(Integer i : set){System.out.println(i);}}

題目要求

給定一個字符串類型的數組str,找到一種拼接方式,使得所有字符串拼接起來形成的字符串具有最小的字典序

  • 字典序:兩個字符串在字典中誰先放在前面,誰的字典序就低
  • 思路:兩個字符串,str1和str2,如果str1+str2的字典順序小于str2+str1,則將str1放到str2的前面,否則將str2放到str1的前面
  • 排序具有傳遞性,不可以歧義,如果是閉環結構是不可以排序的
  • “abc”*“xy”? ==> "abc" * K^2 + "xy" ;* K^2好比與將abc字符串向左邊移動2位,K暗指字符串是K進制的數字,數字2是指第二個需要拼接字符串的位數,然后加上字符串xy,整個的過程就像數字運算一樣。
  • 使用m(str)= return(K^string長度),所以“abc”*“xy”? ==> "abc" * K^2 + "xy" ==> "abc" * m(xy) + "xy"

代碼

package class07;import java.util.Arrays;
import java.util.Comparator;public class Code02_LowestLexicography {public static class MyComparator implements Comparator<String> {@Overridepublic int compare(String a, String b) {return (a + b).compareTo(b + a);}}public static String lowestString(String[] strs) {if (strs == null || strs.length == 0) {return "";}Arrays.sort(strs, new MyComparator());String res = "";for (int i = 0; i < strs.length; i++) {res += strs[i];}return res;}public static void main(String[] args) {String[] strs1 = { "jibw", "ji", "jp", "bw", "jibw" };System.out.println(lowestString(strs1));String[] strs2 = { "ba", "b" };System.out.println(lowestString(strs2));}}

圖片解析

  • 根據給出的條件a . b 小于等于 b . a 和 b. c?小于等于 c?. b得出a . c 小于等于 c .?a,根據上面的式子,得出右邊的不等式,將第一個不等式的兩邊減去b 再乘以 c;第二個不等式左右兩邊 減去c 乘以a ,這樣兩個式子會產生一個重合的項,鏈接其余不等式,化簡之后就可以得到 m(c)* a + c 小于等于 m(a)*c + a
  • ?

比較排序的過程:

分金條問題

思路

  • 利用小根堆來做,每次選取其中最小的兩個數,合并成為一個數,放入到堆中,依次類推。當小根堆里面只有一個數字的時候,就是最終的答案。(哈夫曼編碼

代碼

package class07;import java.util.Comparator;
import java.util.PriorityQueue;public class Code03_LessMoneySplitGold {public static int lessMoney(int[] arr) {PriorityQueue<Integer> pQ = new PriorityQueue<>();for (int i = 0; i < arr.length; i++) {pQ.add(arr[i]);}int sum = 0;int cur = 0;while (pQ.size() > 1) {cur = pQ.poll() + pQ.poll();sum += cur;pQ.add(cur);}return sum;}public static class MinheapComparator implements Comparator<Integer> {@Overridepublic int compare(Integer o1, Integer o2) {return o1 - o2; // < 0  o1 < o2  負數}}public static class MaxheapComparator implements Comparator<Integer> {@Overridepublic int compare(Integer o1, Integer o2) {return o2 - o1; // <   o2 < o1}}public static void main(String[] args) {// solutionint[] arr = { 6, 7, 8, 9 };System.out.println(lessMoney(arr));int[] arrForHeap = { 3, 5, 2, 7, 0, 1, 6, 4 };// min heapPriorityQueue<Integer> minQ1 = new PriorityQueue<>();for (int i = 0; i < arrForHeap.length; i++) {minQ1.add(arrForHeap[i]);}while (!minQ1.isEmpty()) {System.out.print(minQ1.poll() + " ");}System.out.println();// min heap use ComparatorPriorityQueue<Integer> minQ2 = new PriorityQueue<>(new MinheapComparator());for (int i = 0; i < arrForHeap.length; i++) {minQ2.add(arrForHeap[i]);}while (!minQ2.isEmpty()) {System.out.print(minQ2.poll() + " ");}System.out.println();// max heap use ComparatorPriorityQueue<Integer> maxQ = new PriorityQueue<>(new MaxheapComparator());for (int i = 0; i < arrForHeap.length; i++) {maxQ.add(arrForHeap[i]);}while (!maxQ.isEmpty()) {System.out.print(maxQ.poll() + " ");}}}

求獲取的最大錢數

例子?

  • 按照花費的錢建立小根堆,這個是被鎖定的狀態,根據初始的錢,比如w=2,解鎖(1,3)和(2,6)?,按照利潤的高低,壓入利潤大根堆中,(2,6)(1,3)加入棧中,然后將其從小根堆中刪除。然后做第一個項目(2,6),此時自己的錢數為8,那么將小于8的花費的項目解鎖,以此類推。

代碼

package class07;import java.util.Comparator;
import java.util.PriorityQueue;public class Code05_IPO {public static class Node {public int p;public int c;public Node(int p, int c) {this.p = p;this.c = c;}}public static class MinCostComparator implements Comparator<Node> {@Overridepublic int compare(Node o1, Node o2) {return o1.c - o2.c;}}public static class MaxProfitComparator implements Comparator<Node> {@Overridepublic int compare(Node o1, Node o2) {return o2.p - o1.p;}}public static int findMaximizedCapital(int k, int W, int[] Profits, int[] Capital) {PriorityQueue<Node> minCostQ = new PriorityQueue<>(new MinCostComparator());PriorityQueue<Node> maxProfitQ = new PriorityQueue<>(new MaxProfitComparator());// 所有項目扔到被鎖池中, 花費組織的小根堆for (int i = 0; i < Profits.length; i++) {minCostQ.add(new Node(Profits[i], Capital[i]));}for (int i = 0; i < k; i++) { // 進行K輪// 能力所及的項目,全解鎖while (!minCostQ.isEmpty() && minCostQ.peek().c <= W) {maxProfitQ.add(minCostQ.poll());}if (maxProfitQ.isEmpty()) {return W;}W += maxProfitQ.poll().p;}return W;}}

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/447209.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/447209.shtml
英文地址,請注明出處:http://en.pswp.cn/news/447209.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

算法入門篇九 暴力遞歸

牛客網 左程云老師的算法入門課 暴力遞歸 原則 漢諾塔問題 問題 打印n層漢諾塔從左邊移動到最右邊的過程 思想 一共六個過程&#xff0c;左到右、左到中&#xff0c;中到左&#xff0c;中到右&#xff0c;右到左&#xff0c;右到中&#xff0c;互相嵌套使用 左到右 將1…

rtsp和sdp

RTSP 是由Realnetwork 和Netscape共同提出的如何有效地在IP網絡上傳輸流媒體數據的應用層協議 。 實時流協議&#xff08;RTSP&#xff09;建立并控制一個或幾個時間同步的連續流媒體&#xff0c;如音頻和視頻。盡管連續媒體流與控制流交叉是可能的&#xff0c;RTSP本身并不發…

使用javascript實現對于chineseocr的API調用

ChineseOCR在線API 網頁地址 界面 提供多種接口調用方式&#xff0c;比如在線調用、Javascript api調用、curl api調用和python api調用四種方式&#xff0c;本次使用javascript api調用的方式進行OCR識別在線Javascript工具 在線工具網頁鏈接在線Base64 轉化工具 在線工具…

移動流媒體業務的技術與標準

1 引言   流媒體業務是從Internet上發展起來的一種多媒體應用&#xff0c;指使用流&#xff08;Streaming&#xff09;方式在網絡上傳輸的多媒體文件&#xff0c;包括音頻、視頻和動畫等。   流媒體傳輸技術的主要特點是以流&#xff08;streaming&#xff09;的形式進行多…

使用python實現對于chineseocr的API調用

ChineseOCR在線API 網頁鏈接 界面 提供多種接口調用方式&#xff0c;比如在線調用、Javascript api調用、curl api調用和python api調用四種方式&#xff0c;本次使用javascript api調用的方式進行OCR識別在線Base64 轉化工具 Base64在線小工具代碼修改 新增一個變量fill_w…

UDP穿透NAT

NAT(Network AddressTranslators)&#xff0c;網絡地址轉換&#xff1a; 網絡地址轉換是在IP地址日益缺乏的情況下產生的&#xff0c;它的主要目的就是為了能夠地址重用。NAT分為兩大類&#xff0c;基本的NAT和NAPT(Network Address/Port Translator)。 最開始NAT是運行在路由器…

算法入門篇十 圖

圖的存儲方式 臨接表臨接矩陣 表達 點集/邊集有向圖/無向圖 Graph&#xff08;大結構就是圖&#xff09;&#xff08;包含點集合和邊集合&#xff09; import java.util.HashMap; import java.util.HashSet;public class Graph {public HashMap<Integer, Node> nodes;…

SDP協議 學習筆記

SDP:Session Description ProtocolSDP格式:Session descriptionv (protocolversion)o (owner/creatorand session identifier)s (sessionname)i* (sessioninformation)u* (URI ofdescription)e* (emailaddress)p* (phonenumber)c*(connection information - not required if in…

以太坊私有鏈 使用dev模式

dev 使用dev模式&#xff0c;創建一個管理員賬號&#xff0c;控制挖礦&#xff0c;將證明機制改為POA啟動dev模式&#xff0c;需要重新創建一個文件夾&#xff0c;重新搭建私有鏈條 命令 mkdir myDevChain cd myDevChain geth --datadir . --dev console 2>output.log 實…

超文本傳輸協議

超文本傳輸協議 超文本傳輸協議超文件傳輸協定(HTTP&#xff0c;HyperTextTransfer Protocol)是因特網上應用最為廣泛的一種網絡傳輸協定。所有的WWW文件都必須遵守這個標準。設計HTTP最初的目的是為了提供一種發布和接收HTML頁面的方法。 目錄 介紹請求信息請求方法安全方法超…

以太坊區塊鏈 JSON-RPC

RPC定義 以太坊客戶端提供了API和一組遠程調用的&#xff08;RPC&#xff09;命令&#xff0c;這些命令被編碼成json的格式&#xff0c;被叫做JSON-RPC-API。本質上&#xff0c;JSON-RPC API就是一個接口&#xff0c;允許我們編寫的程序使用以太坊客戶端作為網關&#xff0c;訪…

利用MFC調用libvlc.dll作一個簡單的播放器

簡單介紹MFC調用libvlc.dll作一個簡單的播放器&#xff0c;拋磚引玉&#xff0c;各位VC達人繼續深入研究&#xff0c;Jeremiah對VC確實不太感興趣&#xff0c;所以就不做太深入的研究了。2009.10.29修改&#xff1a;加入clip_children屬性設置。參開第1步。環境&#xff1a; …

對于以太坊虛擬機 (EVM)及其相關知識的講解

以太坊虛擬機&#xff08;EVM&#xff09; EVM是智能合約的運行環境作為區塊驗證協議的一部分&#xff0c;參與網絡的每個節點都會運行EVM&#xff0c;審查節點會檢查驗證正在驗證的區塊中列出的交易&#xff0c;并運行EVM中交易觸發的代碼EVM是沙盒封裝的&#xff0c;并且是完…

對于以太坊的Solidity語言介紹

Solidity是什么 Solidity是一門面向合約的、為實現智能合約而創建的高級編程語言&#xff0c;主要目的是為了在以太坊虛擬機&#xff08;EVM&#xff09;上運行Solidity是靜態語言&#xff0c;支持繼承、庫和復雜的用戶定義等特性內含的類型除了常見的編程語言中的標準類型&am…

live555 接收rtsp視頻流流程分析

live555 接收rtsp視頻流流程分析 RTSP交互流程 C表示RTSP客戶端&#xff0c;S表示RTSP服務端 ① C->S: OPTIONrequest //詢問S有哪些方法可用 S->C: OPTION response //S回應信息中包括提供的所有可用方法 ② C->S: DESCRIBErequest //要求得到S…

使用Remix編寫Solidity語言的小例子

設置數值/取數值/加法運算 講解 uint默認使用256位數的整型view表示這個函數僅僅對于數據僅僅是讀取&#xff0c;沒有修改操作returns(uint )&#xff0c;如果單純指定uint&#xff0c;返回的是函數體內的return值&#xff0c;如果包含uint sum,uint SAD_a&#xff0c;那么返…

RTP協議棧簡介

流媒體指的是在網絡中使用流技術傳輸的連續時基媒體&#xff0c;其特點是在播放前不需要下載整個文件&#xff0c;而是采用邊下載邊播放的方式&#xff0c;它是視頻會議、IP電話等應用場合的技術基礎。RTP是進行實時流媒體傳輸的標準協議和關鍵技術&#xff0c;本文介紹如何在L…

深入理解Solidity

Solidity源文件布局 pragma&#xff08;版本雜注&#xff09; 用于指定源文件的版本&#xff0c;表明編譯器的版本&#xff0c;例如 pragma solidity ^0.4.0^用于指代版本號需要大于0.4.0但是不可以超過大的層級&#xff0c;必須小于0.5.0也可以使用大于等于小于來指定版本 i…

H264 流媒體 編碼匯總

實時傳輸協議&#xff08;RTP&#xff09;和實時控制協議&#xff08;RTCP&#xff09; RTP是一種提供端對端傳輸服務的實時傳輸協議&#xff0c;用來支持在單目標廣播和多目標廣播網絡服務中傳輸實時數據&#xff0c;而實時數據的傳輸則由RTCP協議來監視和控制。 RTP定義在RFC…

使用多線程的方式調用chineseocr_API

ChineseOCR在線API 網頁鏈接 界面 提供多種接口調用方式&#xff0c;比如在線調用、Javascript api調用、curl api調用和python api調用四種方式&#xff0c;本次使用javascript api調用的方式進行OCR識別代碼 import glob import base64 import os import requests import …