前言:最近刷了好多leetcode算法題,你們知道,程序=數據結構+算法,因而可知,算法真的是很重要的呢。閒話少談,切入正題,來看看小編以爲有點意思的5題算法題吧...java
給定一個 m x n 的矩陣,若是一個元素爲 0,則將其所在行和列的全部元素都設爲 0。git
這是一個二維數組,咱們只須要遍歷一遍這個二維數組,把元素爲0的那個位置所在的行與列分別標記起來,能夠放在一個HashSet中,咱們都知道,Set是一種無序不重複的集合,而List是有序可重複的,所以在這裏小編選用兩個Set來存儲標記好的下標索引,遍歷完獲得這兩個HashSet後,從HashSet中取得這些全部爲0行列的索引後,咱們就能夠把原二維數組的某一行,某一列所有置爲0便可。github
值得注意的是,咱們不能夠一邊標記一邊置零,由於這樣操做會影響結果,因此咱們只能夠遍歷一遍,用來標記,再遍歷一遍。用來置零。算法
package com.hx.leetcode.L_201910; import java.util.HashSet; import java.util.Set; /** * @author: wenhx * @date: Created in 2019/10/1 23:03 * @description: LeetCode_73:矩陣置零 * @level: middle * @status: finish * @version: $1.0 */ public class LeetCode_73 { /** * 將矩陣中全部0的行列置爲0 */ public void setZeroes(int[][] matrix) { // 定義兩個集合用來存放爲0全部的下標 Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if (matrix[i][j] == 0) { set1.add(i); set2.add(j); } } } // 行置爲0 for (Integer a : set1 ) { for (int j = 0; j < matrix[0].length; j++) { matrix[a][j] = 0; } } // 列置爲0 for (Integer b : set2 ) { for (int i = 0; i < matrix.length; i++) { matrix[i][b] = 0; } } } /** * 主方法:用來測試算法 * @param args */ public static void main(String[] args) { LeetCode_73 leetCode_73 = new LeetCode_73(); int[][] matrix = {{0,1,2,0}, {3,4,5,2}, {1,3,1,5}}; leetCode_73.setZeroes(matrix); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { System.out.print(matrix[i][j] + " "); } } } }
在《英雄聯盟》的世界中,有一個叫 「提莫」 的英雄,他的攻擊可讓敵方英雄艾希(寒冰射手)進入中毒狀態。如今,給出提莫對艾希的攻擊時間序列和提莫攻擊的中毒持續時間,你須要輸出艾希的中毒狀態總時長。數組
你能夠認爲提莫在給定的時間點進行攻擊,並當即使艾希處於中毒狀態。微信
這條題目的入參是一個數組,用來記錄提莫攻擊的時間點,還有一箇中毒的持續時間。咱們能夠先處理一下這個關於時間點的數組,相鄰時間點的差值就是時間間隔,所以能夠推出一個關於時間間隔的數組。假設時間點數組長度爲n,那麼時間間隔數組的長度就是n-1。獲得這個時間間隔數組以後,再來處理中毒時間就很容易了數據結構
咱們先有一個記錄總中毒時間的變量,而後遍歷時間間隔數組,假如間隔值大於或者等於中毒持續時間,則總中毒時間加單次中毒持續的時間;假如間隔值小於中毒持續時間,則加上間隔值便可。app
package com.hx.leetcode.L_201910; /** * @author: wenhx * @date: Created in 2019/10/5 12:03 * @description: LeetCode_495:提莫攻擊 * @level: middle * @status: finish * @version: $1.0 */ public class LeetCode_495 { /** * 計算中毒狀態總時長 */ public int findPoisonedDuration(int[] timeSeries, int duration) { int sum = 0; if (timeSeries.length == 0) { return 0; } if (timeSeries.length == 1) { return duration; } // n個時間點有n-1個時間間隔 int[] timeInterval = new int[timeSeries.length - 1]; for (int i = 0; i < timeInterval.length; i++) { timeInterval[i] = timeSeries[i + 1] - timeSeries[i]; } // 根據時間間隔來判斷中毒秒數 for (int i = 0; i < timeInterval.length; i++) { if (timeInterval[i] >= duration) { sum += duration; } else { sum += timeInterval[i]; } } return sum + duration; } public static void main(String[] args) { LeetCode_495 leetCode_495 = new LeetCode_495(); int[] timeSeries = {1, 4}; int duration = 2; System.out.println("中毒狀態總時長爲:" + leetCode_495.findPoisonedDuration(timeSeries, duration)); } }
給定一個未排序的整數數組,找出其中沒有出現的最小的正整數。dom
求缺失的第一個正數,那個先定義一個變量j來記錄,j從1開始。測試
package com.hx.leetcode.L_201909; import java.util.Arrays; /** * @author: wenhx * @date: Created in 2019/9/26 09:23 * @description: LeetCode_41:缺失的第一個正數 * @level: hard * @status: finish * @version: $1.0 */ public class LeetCode_41 { /** * 計算缺失的第一個正數 */ public int firstMissingPositive(int[] nums) { // 對數組進行排序 Arrays.sort(nums); // 定義一個從1開始自增的正數 int j = 1; // 定義一個臨時變量,用來判斷相鄰值是否相同 int temp = 0; for (int i = 0; i < nums.length; i++) { // 當數組中某值大於自增j時 if (nums[i] > j) { return j; } // 當數組中某值大於0而且不大於j時 else if (nums[i] > 0 && nums[i] <= j) { // 數組中連續同樣 if (temp == nums[i]) { continue; } j++; } else { continue; } // 更新臨時變量 temp = nums[i]; } return j; } public static void main(String[] args) { LeetCode_41 leetCode_41 = new LeetCode_41(); int[] nums = {1, 2, 0}; System.out.println("缺失的第一個正數爲:" + leetCode_41.firstMissingPositive(nums)); } }
TinyURL是一種URL簡化服務。要求:設計一個 TinyURL 的加密 encode 和解密 decode 的方法。你的加密和解密算法如何設計和運做是沒有限制的,你只須要保證一個URL能夠被加密成一個TinyURL,而且這個TinyURL能夠用解密方法恢復成本來的URL。
當你輸入一個URL https://leetcode.com/problems/design-tinyurl 時
它將返回一個簡化的URL http://tinyurl.com/4e9iAk.
這條題目主要是模擬對url的加密與解密,經過HashMap能夠很好的處理加密前與加密後的映射。
加密後的url前綴格式有「http://tinyurl.com/」,問題是後面的6位隨機碼如何產生呢?很簡單,本身寫一個算法唄!看下列代碼,可複用喔~
package com.hx.leetcode.L_201910; import java.util.HashMap; import java.util.Random; /** * @author: wenhx * @date: Created in 2019/10/7 11:44 * @description: LeetCode_535:TinyURL的加密與解密 * @level: middle * @status: finish * @version: $1.0 */ public class LeetCode_535 { private HashMap hashMap = new HashMap<String, String>(); /** * 加密:將一個長的url轉換爲一個短的url * @param longUrl * @return */ public String encode(String longUrl) { String keyString = "http://tinyurl.com/" + getRandomString(6); hashMap.put(keyString, longUrl); return keyString; } /** * 解密:將一個短的url轉換爲一個長的url * @param shortUrl * @return */ public String decode(String shortUrl) { return (String) hashMap.get(shortUrl); } /** * 自定義方法:產生6位數的字符串隨機碼 * @param length * @return */ public static String getRandomString(int length) { String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Random random = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { int number = random.nextInt(62); sb.append(str.charAt(number)); } return sb.toString(); } /** * 主方法:用來測試一下 * @param args */ public static void main(String[] args) { LeetCode_535 codec = new LeetCode_535(); String longUrl = "https://leetcode.com/problems/design-tinyurl"; String shortUrl = codec.encode(longUrl); System.out.println("加密後的url是:" + shortUrl); System.out.println("解密後的url是:" + codec.decode(shortUrl)); } }
給定一個只包括 '(',')','{','}','[',']' 的字符串,判斷字符串是否有效。
有效字符串需知足:
左括號必須用相同類型的右括號閉合。
左括號必須以正確的順序閉合。
注意空字符串可被認爲是有效字符串。
這裏括號的匹配,用棧能夠很好地解決這個問題。咱們都知道,棧是一個後進先出的數據結構,將一個具備()[]{}的字符串從後面開始,一個一個地壓入棧中,壓第一個,而後再拿字符串中相對最後一個括號與棧中棧頂元素匹配,例如 ")"與"("匹配,"]"與"["匹配,"}"與"{"匹配。這裏值得注意的是,棧頂的括號必須是右括號,而字符串尾部的括號必須是左括號。
package com.hx.leetcode.L_Before; import java.util.Stack; /** * @author: wenhx * @date: Created in 2019/9/25 10:58 (以前) * @description: LeetCode_20:有效的括號 * @level: simple * @status: finish * @version: $1.0 */ public class LeetCode_20 { /** * 計算是否有效的括號 */ public boolean isValid(String s) { Stack<String> m = new Stack<>(); while (!s.isEmpty()) { if (m.empty()) { m.push(s.substring(s.length() - 1)); } else { if (m.peek().equals(")") && s.substring(s.length() - 1).equals("(") || m.peek().equals("]") && s.substring(s.length() - 1).equals("[") || m.peek().equals("}") && s.substring(s.length() - 1).equals("{")) { m.pop(); } else { m.push(s.substring(s.length() - 1)); } } s = s.substring(0, s.length() - 1); } if (m.empty()) { return true; } else { return false; } } public static void main(String[] args) { LeetCode_20 leetCode_20 = new LeetCode_20(); String s = "{[]}()"; System.out.println(leetCode_20.isValid(s)); } }
好啦,今天就先到這啦,以上算法純屬小編我的想法,若有疑惑能夠私信或者留言,蟹蟹你們。一塊兒談論,一塊兒進步。
小夥伴們後續有時間小編會常常跟新的嘿嘿...
後續
我的博客地址:https://www.cnblogs.com/q964024886/
GitHub地址:https://github.com/wenhaixiong
微信公衆號: