LeetCode -- Flora -- edit 2025-04-16

1.兩數之和

1. 兩數之和

給定一個整數數組?nums?和一個整數目標值?target,請你在該數組中找出?和為目標值?target? 的那?兩個?整數,并返回它們的數組下標。

你可以假設每種輸入只會對應一個答案,并且你不能使用兩次相同的元素。

你可以按任意順序返回答案。

示例 1:

輸入:nums = [2,7,11,15], target = 9
輸出:[0,1]
解釋:因為 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

示例 2:

輸入:nums = [3,2,4], target = 6
輸出:[1,2]

示例 3:

輸入:nums = [3,3], target = 6
輸出:[0,1]

提示:

  • 2 <= nums.length <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • 只會存在一個有效答案

進階:你可以想出一個時間復雜度小于?O(n2)?的算法嗎?

我的

    public int[] twoSum(int[] nums, int target) {Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();for(int i=0;i<nums.length;i++){int temp = target - nums[i];if(hashtable!=null && hashtable.containsKey(temp)){return new int[]{hashtable.get(temp),i};}hashtable.put(nums[i],i);}return null;}

別人的

class Solution {public int[] twoSum(int[] nums, int target) {int length = nums.length;for(int i = 0; i < length - 1; i++){int back_i = length - i - 1;for(int j = i + 1; j < length; j++){int back_j = length - j - 1;if(nums[i] + nums[j] == target){return new int[]{i,j};}if(nums[back_i] + nums[back_j] == target){return new int[]{back_i, back_j};}}}return new int[0];}
}

思路不一樣:

思路不一樣 每次不止比較1對數的和

2.字母異位詞分組

49. 字母異位詞分組

給你一個字符串數組,請你將?字母異位詞?組合在一起。可以按任意順序返回結果列表。

字母異位詞?是由重新排列源單詞的所有字母得到的一個新單詞。

示例 1:

輸入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
輸出: [["bat"],["nat","tan"],["ate","eat","tea"]]

示例 2:

輸入: strs = [""]
輸出: [[""]]

示例 3:

輸入: strs = ["a"]
輸出: [["a"]]

提示:

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i]?僅包含小寫字母

我的

class Solution {public static List<List<String>> groupAnagrams(String[] strs) {List<List<String>> resData = new ArrayList<>();for(int i = 0 ; i<strs.length ; i++){String sortedString = sortString(strs[i]);if(resData.size() == 0){List<String> innerList = new LinkedList<>();innerList.add(sortedString);innerList.add(strs[i]);resData.add(innerList);}else{Boolean isOld = false;for(int j = 0 ; j<resData.size(); j++){String existingSortedString = resData.get(j).get(0);if(sortedString.equals(existingSortedString)){List<String> innerList = resData.get(j);innerList.add(strs[i]);resData.set(j,innerList);isOld = true;break;}}if (!isOld){//isNewList<String> innerList = new ArrayList<>();innerList.add(sortedString);innerList.add(strs[i]);resData.add(innerList);}}}for(int j = 0 ; j<resData.size(); j++){List<String> innerList = resData.get(j);innerList.remove(0);resData.set(j,innerList);}// 按內部 List 的 size 升序排序Collections.sort(resData, new Comparator<List<?>>() {@Overridepublic int compare(List<?> list1, List<?> list2) {return Integer.compare(list1.size(), list2.size());}});return resData;}public static String sortString(String input) {// 將字符串轉換為字符數組char[] charArray = input.toCharArray();// 對字符數組進行排序Arrays.sort(charArray);// 將排序后的字符數組轉換為字符串return new String(charArray);}}

別人的

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Solution {public List<List<String>> groupAnagrams(String[] strs) {return new AbstractList<List<String>>() {private final List<List<String>> list = new ArrayList<>();public void initList() {if (list.isEmpty()) {Map<String, List<String>> map = new HashMap();for(String s:strs){char[] cc=s.toCharArray();Arrays.sort(cc);String key =Arrays.toString(cc);List<String>list=map.getOrDefault(key, new ArrayList());list.add(s);map.put(key,list);}list.addAll(map.values());}}@Overridepublic List<String> get(int index) {initList();return list.get(index);}@Overridepublic int size() {initList();return list.size();}};}}

?思路一樣,實現方式的優化:

確定每個字符串通過同一排序規則得到唯一排序字符串,由此判斷是否為由相同字母組成的字符串,加入到同一list
去掉每個內層list的第一位
按內層list的size從小到大排序

0.1.代碼總結

    public static void main(String[] args) {// 1int[] nums = {2,7,11,15};int target = 9;int[] twoSum = twoSum2(nums, target);System.out.println(Arrays.toString(twoSum));// 2String[] strs = {"eat","tea","tan","ate","nat","bat"};List<List<String>> groupAnagrams = groupAnagrams2(strs);System.out.println(groupAnagrams);}public static int[] twoSum2(int[] nums, int target) {//思路不一樣 每次不止比較1對數的和int length = nums.length;for(int i = 0; i < length - 1; i++){int back_i = length - i - 1;for(int j = i + 1; j < length; j++){int back_j = length - j - 1;if(nums[i] + nums[j] == target){return new int[]{i,j};}if(nums[back_i] + nums[back_j] == target){return new int[]{back_i, back_j};}}}return new int[0];}//2-answerpublic static List<List<String>> groupAnagrams2(String[] strs) {return new AbstractList<List<String>>() {private final List<List<String>> list = new ArrayList<>();public void initList() {if (list.isEmpty()) {Map<String, List<String>> map = new HashMap();for(String s:strs){//1.sort 思路:確定每個字符串通過同一排序規則得到唯一排序字符串char[] cc=s.toCharArray();Arrays.sort(cc);String key = Arrays.toString(cc);//2.addList 由唯一排序字符串判斷是否為由相同字母組成的字符串,加入到同一listList<String> list = map.getOrDefault(key, new ArrayList());list.add(s);map.put(key, list);}list.addAll(map.values());}}@Overridepublic List<String> get(int index) {initList();return list.get(index);}@Overridepublic int size() {initList();return list.size();}};}//1-mypublic static int[] twoSum(int[] nums, int target) {Map<Integer, Integer> map = new HashMap<Integer, Integer>();for(int i=0;i<nums.length;i++){int temp = target - nums[i];//思路if(map!=null && map.containsKey(temp)){return new int[]{map.get(temp),i};}map.put(nums[i],i);}return null;}//2-mypublic static List<List<String>> groupAnagrams(String[] strs) {//思路:確定每個字符串通過同一排序規則得到唯一排序字符串,由此判斷是否為由相同字母組成的字符串加入到同一list//去掉每個內層list的第一位//按內層list的size從小到大排序List<List<String>> resData = new ArrayList<>();for(int i = 0 ; i<strs.length ; i++){String sortedString = sortString(strs[i]);if(resData.size() == 0){List<String> innerList = new LinkedList<>();innerList.add(sortedString);innerList.add(strs[i]);resData.add(innerList);}else{Boolean isOld = false;for(int j = 0 ; j<resData.size(); j++){String existingSortedString = resData.get(j).get(0);if(sortedString.equals(existingSortedString)){List<String> innerList = resData.get(j);innerList.add(strs[i]);resData.set(j,innerList);isOld = true;break;}}if (!isOld){//isNewList<String> innerList = new ArrayList<>();innerList.add(sortedString);innerList.add(strs[i]);resData.add(innerList);}}}for(int j = 0 ; j<resData.size(); j++){List<String> innerList = resData.get(j);innerList.remove(0);resData.set(j,innerList);}// 按內部 List 的 size 升序排序Collections.sort(resData, new Comparator<List<?>>() {@Overridepublic int compare(List<?> list1, List<?> list2) {return Integer.compare(list1.size(), list2.size());}});return resData;}public static String sortString(String input) {// 將字符串轉換為字符數組char[] charArray = input.toCharArray();// 對字符數組進行排序Arrays.sort(charArray);// 將排序后的字符數組轉換為字符串return new String(charArray);}

0.2.相關

AI:使用通俗易懂的例子的來講解AbstractList

看起來用戶可能在學習Java集合框架,特別是想深入理解如何自定義List實現。

用戶可能已經了解了AbstractList的基本用法,但希望有更簡單、生活化的例子來加深理解。他們可能對之前的技術示例感到有些復雜,或者需要更直觀的解釋來鞏固概念。需要將AbstractList的概念與實際生活中的場景結合,幫助用戶形成直觀印象。

需要確定用戶的基礎水平。之前的回答涉及到了代碼示例,所以用戶可能有一定的編程經驗,但可能需要更基礎的比喻或例子。例如,用日常生活中的事物來類比AbstractList的作用,比如菜單、書架等。

用戶的需求不僅僅是知道如何用代碼實現,而是理解AbstractList存在的意義和適用場景。可能需要強調為什么使用AbstractList而不是直接實現List接口,比如減少必須實現的方法數量,提供默認實現等。

另外,用戶可能想知道在什么情況下應該繼承AbstractList,比如需要自定義列表行為,或者包裝現有數據結構。需要提供簡單明了的例子,比如只讀列表、固定大小列表,或者組合多個列表的情況。

需要避免使用過于技術化的術語,轉而使用比喻和簡單代碼示例。例如,用書架的比喻來解釋不可變列表,用購物清單來演示可變列表的實現。同時,對比直接實現List接口和繼承AbstractList的差異,突出AbstractList的便利性。

還要注意用戶可能的誤區,比如認為繼承AbstractList必須實現所有方法,而實際上只需要實現get和size。或者對于修改操作,默認會拋出異常,需要覆蓋set、add等方法才能支持修改。

最后,確保例子涵蓋不同的使用場景,如不可變列表、包裝現有數組、動態擴展的列表等,幫助用戶全面理解AbstractList的靈活性和實用性。

好的!我用一個?「菜單本」?的比喻來幫你理解?AbstractList,并配上一個超簡單的代碼例子。


📖?比喻場景

假設你要做一個?「飯店菜單系統」,但有個特殊要求:

  • 普通服務員只能?查看?菜單(不能修改)

  • 店長有?修改菜單?的權限

如果用?AbstractList?來實現,就像這樣:


🎯?代碼實現

import java.util.AbstractList;
import java.util.Arrays;
import java.util.List;// 自定義菜單類(繼承AbstractList)
class Menu extends AbstractList<String> {private String[] dishes;  // 存儲菜品// 構造方法public Menu(String[] dishes) {this.dishes = Arrays.copyOf(dishes, dishes.length);}// 必須實現的方法1:獲取菜品(普通服務員用)@Overridepublic String get(int index) {return dishes[index];}// 必須實現的方法2:獲取菜單長度@Overridepublic int size() {return dishes.length;}// 可選實現:修改菜品(只有店長能調用)@Overridepublic String set(int index, String newDish) {String oldDish = dishes[index];dishes[index] = newDish;return oldDish;  // 返回被替換的舊菜名}
}public class Test {public static void main(String[] args) {// 初始菜單String[] initialDishes = {"魚香肉絲", "宮保雞丁", "麻婆豆腐"};List<String> menu = new Menu(initialDishes);// 普通服務員查看菜單System.out.println("當前菜單:" + menu);  // 輸出:[魚香肉絲, 宮保雞丁, 麻婆豆腐]// 嘗試修改菜單(會報錯,因為沒權限)// menu.add("水煮魚");  // 拋出 UnsupportedOperationException// 店長修改第二道菜if (menu instanceof Menu) {Menu bossMenu = (Menu) menu;String old = bossMenu.set(1, "辣子雞");System.out.println("替換掉:" + old);  // 輸出:替換掉:宮保雞丁}System.out.println("新菜單:" + menu);  // 輸出:[魚香肉絲, 辣子雞, 麻婆豆腐]}
}

🔑?關鍵點解析

  1. 為什么用 AbstractList?

    • 它幫你實現了?List?接口中大部分復雜方法(如?iterator()

    • 你只需專注實現?get()?和?size()?這兩個核心方法

  2. 修改控制

    • 默認所有修改方法(如?add()remove())會拋出異常

    • 如果想讓某些角色能修改,只需覆蓋對應方法(比如例子中的?set()

  3. 實際應用場景

    • 創建?只讀列表(不覆蓋修改方法)

    • 包裝現有數組(如例子中的?String[] dishes

    • 實現特殊規則的列表(如固定長度列表、組合多個列表)


💡?對比直接實現 List 接口

如果不用?AbstractList,你需要實現?List?接口的?24個方法!而用?AbstractList?只需要實現?2個方法,其他方法已有默認實現。

就像做菜單時,有人幫你寫好了打印菜單、搜索菜品等功能,你只需告訴它「菜品存在哪」和「有多少道菜」。

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

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

相關文章

web后端語言下篇

#作者&#xff1a;允砸兒 #日期&#xff1a;乙巳青蛇年 三月廿一 筆者今天將web后端語言PHP完結一下&#xff0c;后面還會寫一個關于python的番外。 PHP函數 PHP函數它和筆者前面寫的js函數有些許類似&#xff0c;都是封裝的概念。將實現某一功能的代碼塊封裝到一個結構中…

LeetCode 259 題全解析:Swift 快速找出“滿足條件”的三人組

文章目錄 摘要描述示例 1&#xff1a;示例 2&#xff1a;示例 3&#xff1a; 題解答案&#xff08;Swift&#xff09;題解代碼分析示例測試及結果時間復雜度空間復雜度總結 摘要 本文圍繞 LeetCode 259 題“較小的三數之和”&#xff0c;通過 Swift 給出兩種解法&#xff0c;并…

第八節:React HooksReact 18+新特性-React Server Components (RSC) 工作原理

? 與SSR區別&#xff1a;零客戶端JS、服務端數據直出 ? 搭配Next.js 14使用場景 React Server Components (RSC) 工作原理及 Next.js 14 應用場景解析 一、RSC 核心工作原理 React Server Components (RSC) 是 React 18 引入的顛覆性特性&#xff0c;其設計目標是 服務端與…

萬字解析TCP

通過學習視頻加博客的組合形式&#xff0c;整理了一些關于TCP協議的知識。 *圖源&#xff1a;臨界~的csdn博客。 一、TCP建立連接 TCP的建立連接&#xff0c;大致可以分為面向連接、TCP報文結構、TCP的三次握手、TCP的建立狀態、SYN泛洪攻擊。 1.1、面向連接 面向連接 --- …

前端vue+typeScritp+elementPlus基礎頁面實現:

效果&#xff1a; 前端代碼&#xff1a; index.vue: <template><el-container><el-main><el-card class"search-card" shadow"never"><transition :enter-active-class"proxy?.animate.searchAnimate.enter" :le…

微電網與分布式能源:智能配電技術的場景化落地

安科瑞顧強 隨著數字化轉型與能源革命的加速推進&#xff0c;電力系統正經歷從傳統模式向智能化、網絡化方向的深刻變革。用戶側的智能配電與智能用電技術作為這一變革的核心驅動力&#xff0c;正在重塑電力行業的生態格局。本文將從技術架構、應用場景及未來趨勢等維度&#…

綠幕摳圖直播軟件-藍松摳圖插件--使用相機直播,燈光需要怎么打?

使用SONY相機進行綠幕摳圖直播時&#xff0c;燈光布置是關鍵&#xff0c;直接影響摳圖效果和直播畫質。以下是詳細的燈光方案和注意事項&#xff1a; 一、綠幕燈光布置核心原則 均勻照明&#xff1a;綠幕表面光線需均勻&#xff0c;避免陰影和反光&#xff08;亮度差控制在0.5…

Linux Privilege Escalation: LD_PRELOAD

聲明&#xff1a;本文所有操作需在授權環境下進行&#xff0c;嚴禁非法使用&#xff01; 0x01 什么是 LD_PRELOAD&#xff1f; LD_PRELOAD 是 Linux 系統中一個特殊的環境變量&#xff0c;它允許用戶在程序啟動時優先加載自定義的動態鏈接庫&#xff08;.so 文件&#xff09;&…

程序性能(1)嵌入式基準測試工具

程序性能(1)嵌入式基準測試工具 Author&#xff1a;Once Day date: 2025年4月19日 漫漫長路&#xff0c;才剛剛開始… 全系列文檔查看&#xff1a;Perf性能分析_Once-Day的博客-CSDN博客 參考文檔: CPU Benchmark – MCU Benchmark – CoreMark – EEMBC Embedded Micropr…

ArrayList的subList的數據仍是集合

ArrayList的subList結果不可強轉成ArrayList&#xff0c;否則會拋出 ClassCastException異常 ? 級別&#xff1a; 【CRITICAL】 ? 規約類型&#xff1a;BUG ? 最壞影響&#xff1a; 程序錯誤&#xff0c;拋出異常 說明&#xff1a;subList 返回的是ArrayList的內部類SubL…

Notepad++中將文檔格式從Windows(CR LF)轉換為Unix(LF)

在Windows中用記事本寫了一個.sh的Linux運行腳本&#xff0c;是無法直接在Linux中執行&#xff0c;需要首先把文本編碼格式轉換為Unix的&#xff0c;特別是換行符這些&#xff0c;轉換步驟如下&#xff1a; 1、打開文檔 在Notepad中打開需要轉換的文件。 2、進入文檔格式轉換…

使用Ingress發布應用程序

使用Ingress發布應用程序 文章目錄 使用Ingress發布應用程序[toc]一、什么是Ingress二、定義Ingress三、什么是Ingress控制器四、部署nginx Ingress控制器1.了解nginx Ingress控制器的部署方式2.安裝nginx Ingress控制器3.本地實際測試 五、使用Ingress對外發布應用程序1.使用D…

【網絡編程】TCP數據流套接字編程

目錄 一. TCP API 二. TCP回顯服務器-客戶端 1. 服務器 2. 客戶端 3. 服務端-客戶端工作流程 4. 服務器優化 TCP數據流套接字編程是一種基于有連接協議的網絡通信方式 一. TCP API 在TCP編程中&#xff0c;主要使用兩個核心類ServerSocket 和 Socket ServerSocket Ser…

力扣刷題Day 21:兩數之和(1)

1.題目描述 2.思路 暴力解法雖然不超時間限制&#xff0c;但是題解實在太妙了&#xff0c;哈希大法好&#xff01; 3.代碼&#xff08;Python3&#xff09; class Solution:def twoSum(self, nums: List[int], target: int) -> List[int]:hash_table dict()for i, num i…

關于UE5的抗鋸齒和TAA

關于閃爍和不穩定現象的詳細解釋 當您關閉抗鋸齒技術時&#xff0c;場景中會出現嚴重的閃爍和不穩定現象&#xff0c;尤其在有細節紋理和小物體的場景中。這種現象的技術原因如下&#xff1a; 像素采樣問題 在3D渲染中&#xff0c;每個像素只能表示一個顏色值&#xff0c;但…

【MySQL】MySQL建立索引不知道注意什么?

基本原則&#xff1a; 1.選擇性原則&#xff1a; 選擇高選擇性的列建立索引(該列有大量不同的值) 2.適度原則&#xff1a;不是越多越好&#xff0c;每個索引都會增加寫入開銷 列選擇注意事項&#xff1a; 1.常用查詢條件列&#xff1a;WHERE字句中頻繁使用的列 2.連接操作列…

Vue3 + TypeScript中provide和inject的用法示例

基礎寫法&#xff08;類型安全&#xff09; typescript // parent.component.vue import { provide, ref } from vue import type { InjectionKey } from vue// 1. 定義類型化的 InjectionKey const COUNTER_KEY Symbol() as InjectionKey<number> const USER_KEY Sy…

樹莓派超全系列教程文檔--(33)樹莓派啟動選項

樹莓派啟動選項 啟動選項start_file &#xff0c;fixup_filecmdlinekernelarm_64bitramfsfileramfsaddrinitramfsauto_initramfsdisable_poe_fandisable_splashenable_uartforce_eeprom_reados_prefixotg_mode &#xff08;僅限Raspberry Pi 4&#xff09;overlay_prefix配置屬…

java怎么找bug?Arthas原理與實戰指南

Arthas原理與實戰指南 1. Arthas簡介 Arthas是阿里巴巴開源的Java診斷工具&#xff0c;其名字取自《魔獸世界》的人物阿爾薩斯。它面向線上問題定位&#xff0c;被廣泛應用于性能分析、定位問題、安全審計等場景。Arthas的核心價值在于它能夠在不修改應用代碼、不重啟Java進程…

Python自學第1天:變量,打印,類型轉化

突然想學Python了。經過Deepseek的推薦&#xff0c;下載了一個Python3.12安裝。安裝過程請自行搜索。 乖乖從最基礎的學起來&#xff0c;廢話不說了&#xff0c;上鏈接&#xff0c;呃&#xff0c;打錯了&#xff0c;上知識點。 變量的定義 # 定義一個整數類型的變量 age 10#…