Timu-1- B

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

404 Sum of Left Leaves Given the root of a binary tree, return the sum of all left leaves. Input: root = [3,9,20,null,null,15,7] Output: 24 Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.

Base Case: If the input root is null, return 0 since there are no nodes to process. Check for Left Leaves: Initialize a variable result to 0. If the left child of the current root node exists and it is a leaf (both its left and right children are null), add its value to result. Recursive Calls: Recursively call sumOfLeftLeaves for both the left and right subtrees. Add the results of these recursive calls to result. Return the Result: Return the final value of result which accumulates the sum of left leaves. Time Complexity: O(n): The function visits each node exactly once, making the time complexity linear with respect to the number of nodes in the tree. Space Complexity: O(h): The space complexity is proportional to the height of the tree, due to the recursion stack. In the worst case (a skewed tree), this could be O(n).

82 Remove Duplicates from Sorted List II Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. Input: head = [1,2,3,3,4,4,5] Output: [1,2,5]

Base Case Check: If the head of the list is null or the list has only one node, return the head as there are no duplicates to remove. Check for Duplicates: If the value of the current node is the same as the value of the next node, move the head to the next node until the values are different, effectively skipping all nodes with the same value. Recursive Call: Recursively call the deleteDuplicates function on the next distinct node and set it as the next node of the current head if the values are different. Return the Modified List: Return the modified list with duplicates removed. Time Complexity: O(n): The function iterates through the list once, making it linear in terms of the number of nodes. Space Complexity: O(n): The recursion stack can go as deep as the number of nodes in the worst case.

202 Happy Number Write an algorithm to determine if a number n is happy. 「快乐数」 定义为: 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。 然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。 如果这个过程 结果为 1,那么这个数就是快乐数。 如果 n 是 快乐数 就返回 true ;不是,则返回 false 。 输入:n = 19 输出:true 解释: 1^2 + 9^2 = 82 8^2 + 2^2 = 68 6^2 + 8^2 = 100 1^2 + 0^2 + 0^2 = 1

Base Case Check: If the input number n is 1 or 7, return true because these are known happy numbers. If n is less than 10 but not 1 or 7, return false because a single-digit number (other than 1 or 7) cannot be a happy number. Compute the Sum of Squares of Digits: Initialize m to 0. This will store the sum of the squares of the digits of n. While n is not 0, extract the last digit of n (using n % 10), square it, and add it to m. Remove the last digit from n (using n / 10). Recursive Call: Recursively call the isHappy function with the new value m. This process repeats until either n becomes a happy number or it becomes a number that cannot lead to 1. Time Complexity: The time complexity is difficult to determine exactly due to the recursive nature and the variance in the number of digits and iterations. However, the process terminates once it finds a happy number or falls into a known non-happy cycle. In general, the complexity can be considered O(log n) due to the division operation reducing the number of digits. Space Complexity: O(log n): The recursive calls stack up based on the number of digits in n, which reduces by a factor of 10 each iteration.

24 Swap Nodes in Pairs Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes Input: head = [1,2,3,4] Output: [2,1,4,3]

Base Case Handling: If the head is null or the head's next node is null, return the head. This handles the cases where the list is empty or has only one node. Recursive Swapping: Store the second node (head.next) in a variable newNode. Recursively call swapPairs on the sublist starting from the third node (head.next.next). Set the first node's (head) next pointer to the result of the recursive call. Set the second node's (newNode) next pointer to the first node (head). Return the New Head: The second node (newNode) becomes the new head of the swapped pair, so return newNode. Time Complexity: O(n): The function processes each node exactly once. Space Complexity: O(n): The space complexity is O(n) due to the recursion stack for the recursive calls.

2423 Remove Letter To Equalize Frequency You are given a 0-indexed string word, consisting of lowercase English letters. You need to select one index and remove the letter at that index from word so that the frequency of every letter present in word is equal. Return true if it is possible to remove one letter so that the frequency of all letters in word are equal, and false otherwise. Example 1: Input: word = "abcc" Output: true Explanation: Select index 3 and delete it: word becomes "abc" and each character has a frequency of 1.

Count Character Frequencies: Create an array cnt of size 26 to count the frequency of each character in the input string word. Iterate over each character in the string and update the cnt array accordingly. Sort Frequencies: Sort the cnt array to make it easier to check if removing one character can result in equal frequencies of the remaining characters. Remove One Character and Check Frequencies: Initialize a variable start to skip the leading zeros in the cnt array (since not all 26 characters may be present). For each non-zero frequency in the cnt array:Decrement the frequency by 1.Check if the modified cnt array has all equal frequencies using the same helper function.If true, return true immediately.Restore the frequency by incrementing it back. Check if All Frequencies are Equal: The same function checks if all non-zero frequencies in the cnt array are the same. Return the Result: If no such removal results in equal frequencies, return false. Time Complexity: O(n + 26 log 26 + 26^2): Counting character frequencies is O(n), sorting the 26-length array is O(26 log 26) which is constant, and checking the frequencies involves a nested loop over 26 elements. Space Complexity: O(26): The space complexity is constant as the cnt array has a fixed size of 26.

279 Perfect Squares Given an integer n, return the least number of perfect square numbers that sum to n. 完全平方数 是一个整数,其值等于另一个整数的平方 Example 1: Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4.

Define the Dynamic Programming Array: Create an array dp where dp[i] represents the least number of perfect square numbers that sum to i. Initialize the Array: Fill the array dp with a large value (Integer.MAX_VALUE) to signify that initially, the minimum number of perfect squares to reach each number is unknown. Set dp[0] to 0 since zero is the sum of zero perfect squares. Fill the DP Array: Iterate through each number i from 1 to n. For each i, iterate through each perfect square j*j that is less than or equal to i. Update dp[i] to be the minimum of its current value and dp[i - j*j] + 1. This accounts for including the perfect square j*j in the sum. Return the Result: The value dp[n] will hold the least number of perfect square numbers that sum to n. Time Complexity: The time complexity is O(n√n) because for each i from 1 to n, we iterate through all j such that j*j <= i. Space Complexity: The space complexity is O(n) for the dp array.

950 Reveal Cards In Increasing Order You are given an integer array deck. There is a deck of cards where every card has a unique integer. The integer on the ith card is deck[i]. 重复执行以下步骤,直到显示所有卡牌为止: 从牌组顶部抽一张牌,显示它,然后将其从牌组中移出。 如果牌组中仍有牌,则将下一张处于牌组顶部的牌放在牌组的底部。 如果仍有未显示的牌,那么返回步骤 1。否则,停止行动。 Return an ordering of the deck that would reveal the cards in increasing order. Example 1: Input: deck = [17,13,11,2,3,5,7] Output: [2,13,3,11,5,17,7]

Edge Case Check: Check if the deck is null or has less than one element. If true, return the deck as is. Sort the Deck: Sort the deck array in ascending order. This ensures that we have the cards in the order we want to reveal them. Initialize a Queue: Use a Queue<Integer> to simulate the revealing process. Simulate the Revealing Process in Reverse: Traverse the sorted deck array in reverse order (from the largest element to the smallest). For each card:Add the card to the queue.If it is not the last card in the reverse traversal, move the front element of the queue to the back. This simulates the process of revealing the top card and placing the next top card at the bottom of the deck. Retrieve the Result from the Queue: Convert the queue back into the deck array in reverse order to get the final answer. Time Complexity: O(n log n): Sorting the deck array takes O(n log n) time. O(n): The simulation of the revealing process involves linear operations. Space Complexity: O(n): The queue stores all elements of the deck.

945 Minimum Increment to Make Array Unique You are given an integer array nums. In one move, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1. Return the minimum number of moves to make every value in nums unique. 输入:nums = [3,2,1,2,1,7] 输出:6 解释:经过 6 次 move 操作, 数组将变为 [3, 4, 1, 2, 5, 7]。 可以看出 5 次或 5 次以下的 move 操作是不能让数组的每个值唯一的。

Edge Case Check: Check if the input array A is null or empty. If so, return 0 because there are no increments needed. Sort the Array: Sort the array A to ensure elements are in ascending order. This allows for easy comparison and adjustment of consecutive elements. Initialize Variables: res: To keep track of the total number of increments needed. prev: To keep track of the previous element's value after necessary adjustments. Iterate Through the Array: Start iterating from the second element (index 1) to the end of the array. For each element A[i], calculate the expected value expect as prev + 1 to ensure it is unique. If A[i] is less than or equal to expect, calculate the number of increments needed (expect - A[i]) and add this to res. Update prev to the maximum of expect and A[i] to handle the next element. Return Result: After iterating through the entire array, return res which contains the total number of increments needed to make all elements unique. Time Complexity: O(n log n): The function sorts the array which takes O(n log n) time. The subsequent iteration through the array takes O(n) time. Space Complexity: O(1): The space complexity is constant as only a fixed amount of extra space is used, regardless of the input size.

1048 Longest String Chain You are given an array of words where each word consists of lowercase English letters. wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB. Return the length of the longest possible word chain with words chosen from the given list of words. 输入:words = ["a","b","ba","bca","bda","bdca"] 输出:4 解释:最长单词链之一为 ["a","ba","bda","bdca"]

Edge Case Check: Check if the input array words is null or empty. If so, return 0 because there are no words to form a chain. Sort the Array: Sort the array words based on their lengths in ascending order. This helps in building the word chain incrementally from shorter to longer words. Initialize Variables: res: To keep track of the longest chain length. map: A HashMap to store each word and the length of its maximum chain. Iterate Through the Words: For each word w in the sorted array, initialize its chain length to 1 in the map (map.put(w, 1)). Form potential predecessor words by removing each character from w one at a time and checking if the resulting word is in the map. If the predecessor word is found in the map and its chain length plus 1 is greater than the current chain length of w, update the map with the new chain length for w. Update res with the maximum chain length encountered so far. Return Result: After iterating through all words, return res which contains the length of the longest word chain. Time Complexity: O(n * m * m): The function sorts the array which takes O(n log n) time, where n is the number of words. The nested loops iterate through each word (n times) and for each word, it generates all possible predecessor words by removing one character at a time (m times), and each removal operation on a word of length m takes O(m) time. Space Complexity: O(n * m): The space complexity is mainly due to the HashMap which stores each word and its chain length. The space required for the map is proportional to the number of words and their lengths.

179 Largest Number Given a list of non-negative integers nums, arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer. Example 1: Input: nums = [10,2] Output: "210" Example 2: Input: nums = [3,30,34,5,9] Output: "9534330"

Edge Case Handling: Check if the input array A is null or empty. If it is, return an empty string. Convert Integers to Strings: Convert the integer array A to a string array arr. This allows the numbers to be concatenated and compared as strings. Custom Comparator for Sorting: Sort the string array arr using a custom comparator. The comparator compares two strings a and b by comparing the concatenation results b + a and a + b. This ensures that the combination that forms a larger number appears first. Edge Case for All Zeros: After sorting, if the first character of the first string in arr is '0', return "0". This handles cases where the array contains only zeros. Build the Result: Use a StringBuilder to concatenate the sorted strings and form the final largest number. Time Complexity: The time complexity is O(N log N) due to the sorting step, where N is the number of elements in the array. Space Complexity: The space complexity is O(N) for storing the string representations of the numbers and the final result.

143 Reorder List You are given the head of a singly linked-list. The list can be represented as: L0 → L1 → ... → Ln - 1 → Ln Reorder the list to be on the following form: L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → ... Input: head = [1,2,3,4] Output: [1,4,2,3]

Find the Middle Node: Use two pointers, slow and fast, to find the middle of the linked list. slow moves one step at a time, while fast moves two steps at a time. When fast reaches the end, slow will be at the middle. Reverse the Second Half: Reverse the second half of the linked list starting from the node after the slow pointer. Use a helper function reverse to reverse the linked list. Link the Two Halves Together: Merge the first half and the reversed second half by alternating nodes from each half. Use two pointers to track the nodes in each half and update their next pointers accordingly. Time Complexity: The time complexity is O(N), where N is the number of nodes in the linked list. This is because we traverse the list to find the middle, reverse the second half, and then merge the two halves. Space Complexity: The space complexity is O(1) because we are using a constant amount of extra space for pointers.

1 Two Sum Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. Input: nums = [2,7,11,15], target = 9 Output: [0,1]

Initialize HashMap and Result Array: Create a HashMap map to store the difference between the target and each number as the key, and the index of the number as the value. Create an array res to store the indices of the two numbers that add up to the target. Iterate Through the Array: For each element in nums:Check if the current number exists in the map:If it does, set the indices in res array with the value from map and the current index.Return the res array as the solution.If the current number does not exist in the map, store the difference between the target and the current number as the key, and the current index as the value. Return Result: If no such pair is found, return an array {-1, -1}. Time Complexity: O(n): The algorithm iterates through the nums array once, performing constant-time operations for each element. Space Complexity: O(n): The HashMap stores up to n key-value pairs, where n is the length of the nums array.

3 Longest Substring Without Repeating Characters Given a string s, find the length of the longest substring without repeating characters. Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.

Initial Checks: If the input string s is null or empty, return 0 as the length of the longest substring without repeating characters. Sliding Window Technique: Use two pointers, left and right, to represent the window boundaries. Initialize a Map<Character, Integer> to keep track of the frequency of characters within the window. Initialize a variable len to store the length of the longest substring without repeating characters. Expand the Window: Iterate over the string using the right pointer. Add the current character cur to the map and update its frequency. Move the right pointer to expand the window. Shrink the Window: If the frequency of the current character cur in the map exceeds 1, it means there is a repeating character within the window. Move the left pointer to the right until the frequency of the current character cur becomes 1. Decrease the frequency of characters as the left pointer moves. Update the Maximum Length: After ensuring no repeating characters in the window, update the length len to be the maximum of the current length and the window size (right - left). Return the Result: Return the value of len as the length of the longest substring without repeating characters. Time Complexity: O(n): The right and left pointers each traverse the string s once, resulting in linear time complexity. Space Complexity: O(min(n, m)): The space complexity depends on the size of the character set m and the length of the string n. The map can hold at most the size of the character set (e.g., 26 for lowercase letters, 128 for ASCII characters).

1169 invalid Transactions 如果出现下述两种情况,交易 可能无效: 交易金额超过 $1000 或者,它和 另一个城市 中 同名 的另一笔交易相隔不超过 60 分钟(包含 60 分钟整) Return a list of transactions that are possibly invalid. 输入:transactions = ["alice,20,800,mtv","alice,50,100,beijing"] 输出:["alice,20,800,mtv","alice,50,100,beijing"] 解释:第一笔交易是无效的,因为第二笔交易和它间隔不超过 60 分钟、名称相同且发生在不同的城市。同样,第二笔交易也是无效的。

Initialization and Parsing: Create arrays to store the parsed components (name, time, amount, city) of each transaction. Create a boolean array add to mark invalid transactions. Parse the Transactions: Split each transaction string and store the respective components (name, time, amount, city) in their corresponding arrays. Identify Invalid Transactions: Iterate through the transactions and mark those that are invalid:If a transaction amount exceeds 1000, mark it as invalid.For each transaction, compare it with every subsequent transaction to check if they meet the criteria for being invalid due to occurring within 60 minutes in different cities for the same person. Collect Invalid Transactions: Iterate through the add array, and add the transactions marked as invalid to the result list. Time Complexity: O(n^2): The algorithm involves nested loops to compare each transaction with every other transaction, where n is the number of transactions. Space Complexity: O(n): The space complexity is determined by the arrays used to store transaction components and the boolean array to mark invalid transactions.

264 Ugly Number II 给你一个整数 n ,请你找出并返回第 n 个 丑数 。 丑数 就是质因子只包含 2、3 和 5 的正整数。 示例 1: 输入:n = 10 输出:12 解释:[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] 是由前 10 个丑数组成的序列。

Initialization: Create an array nums containing the prime factors {2, 3, 5}. Create a HashSet named set to store unique ugly numbers and a PriorityQueue named pq to store ugly numbers in ascending order. Initialize set and pq with the first ugly number, which is 1. Generate Ugly Numbers: Use a for loop to generate the first n ugly numbers. In each iteration, poll the smallest number from the priority queue pq. If the current iteration index equals n, return the current number as the nth ugly number. For each prime factor in nums, multiply it with the current number to generate a new ugly number. If the new ugly number is not already in the set, add it to both set and pq. Return Result: If the loop completes without finding the nth ugly number, return -1 (this should not happen in valid input scenarios). Time Complexity: O(n log n): The priority queue operations (insert and delete) are O(log n) and each number is processed once. Space Complexity: O(n): The space complexity is O(n) for storing the ugly numbers in the set and pq.

1043 Partition Array for Maximum Sum Given an integer array arr, partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray. Return the largest sum of the given array after partitioning. 输入:arr = [1,15,7,9,2,5,10], k = 3 输出:84 解释:数组变为 [15,15,15,9,10,10,10]

Initialization: Create an integer n to store the length of the input array A. Create a dp array of size n + 1 to store the maximum sum for subarrays of different lengths. Dynamic Programming Loop: Iterate through the input array A using an index i from 0 to n. For each index i, initialize j to i - 1 and max to dp[i]. Use a while loop to iterate through the subarray of length up to K ending at i. In each iteration:Update max to be the maximum value in the current subarray.Update dp[i] to be the maximum of its current value and the sum of dp[j] plus the product of the current subarray length (i - j) and max.Decrement j to consider the next subarray ending at i. Return Result: Return the value dp[n], which contains the maximum sum of the array after partitioning. Time Complexity: O(n * K): The outer loop runs n times and the inner loop runs up to K times for each iteration of the outer loop. Space Complexity: O(n): The space complexity is O(n) for storing the dp array.

1029 Two City Scheduling A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti. Return the minimum cost to fly every person to a city such that exactly n people arrive in each city. (DP) Example 1: Input: costs = [[10,20],[30,200],[400,50],[30,20]] Output: 110

Initialization: Determine n as half the length of the costs array. Create a 2D dp array of size (n+1) x (n+1) to store the minimum cost for sending i people to city A and j people to city B. Initialize Base Cases: Populate the first column (dp[i][0]) where all i people go to city A. Populate the first row (dp[0][j]) where all j people go to city B. Fill the DP Table: Iterate over the dp array and fill in the values by choosing the minimum cost between sending the next person to city A or city B. dp[i][j] = Math.min(dp[i - 1][j] + costs[i + j - 1][0], dp[i][j - 1] + costs[i + j -1][1]); Return the Result: The minimum cost to send n people to city A and n people to city B will be stored in dp[n][n]. Time Complexity: O(n^2): The algorithm involves filling up an (n+1) x (n+1) DP table. Space Complexity: O(n^2): The space complexity is determined by the DP table of size (n+1) x (n+1).

1029 Two City Scheduling 公司计划面试 2n 人。给你一个数组 costs ,其中 costs[i] = [aCosti, bCosti] 。第 i 人飞往 a 市的费用为 aCosti ,飞往 b 市的费用为 bCosti 。 返回将每个人都飞到 a 、b 中某座城市的最低费用,要求每个城市都有 n 人抵达。

Initialization: Determine the number of people N from the length of the costs array. Create an array refund to store the cost difference between sending each person to city B instead of city A. Initialize minCost to accumulate the minimum cost, starting by sending everyone to city A. Calculate Refunds and Initial Cost: Iterate through each cost pair in costs. Calculate the refund for each person as cost[1] - cost[0] (i.e., the cost difference between city B and city A). Add the cost of sending everyone to city A to minCost. Sort Refunds: Sort the refund array to determine which people will have the most favorable refunds when sent to city B. Adjust Cost by Sending Some People to City B: Iterate through the first half of the sorted refund array (i.e., the N/2 smallest refunds). Adjust minCost by adding these refunds, which will reduce the total cost. Return the Minimum Cost: The final minCost after adjustments represents the minimum total cost to send N/2 people to city A and N/2 people to city B. Time Complexity: O(n log n): Sorting the refund array takes O(n log n) time, where n is the number of people. The other operations (initial cost calculation and adjusting the cost) are linear, O(n). Space Complexity: O(n): The space complexity is primarily due to the refund array which stores cost differences for n people.

1244 Design A Leaderboard 排行榜 addScore(playerId, score): Update the leaderboard by adding score to the given player's score. If there is no player with such id in the leaderboard, add him to the leaderboard with the given score. top(K): Return the score sum of the top K players. reset(playerId): Reset the score of the player with the given id to 0 (in other words erase it from the leaderboard). It is guaranteed that the player was added to the leaderboard before calling this function.

Initialization: Use a HashMap<Integer, Integer> (user_score) to map each player ID to their current score. Use a TreeMap<Integer, HashSet<Integer>> (score_users) to map scores to sets of player IDs. The TreeMap is sorted in descending order of scores. Add Score: If the player does not exist in user_score, initialize their score to 0. Update the player's score by adding the given score to their current score. Update score_users by removing the player from the set of their old score and adding them to the set of their new score. Top K Scores: Traverse the score_users map to sum the top K scores. Continue summing scores until you have included K players. If you encounter a score with fewer than K players, add all those players' scores to the sum and reduce K accordingly. Stop once you have included K players and return the sum. Reset: If the player does not exist in user_score, return immediately. Remove the player from user_score. Remove the player from their corresponding score set in score_users. If the score set becomes empty after removal, remove the score from score_users. Time Complexity: Add Score: O(log n) for updating the TreeMap, where n is the number of different scores. Top K: O(K log n), since we may need to iterate through up to K different scores in the TreeMap. Reset: O(log n) for updating the TreeMap. Space Complexity: O(u + s), where u is the number of users and s is the number of unique scores.

230 Kth Smallest Element in a BST Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree. Input: root = [3,1,4,null,2], k = 1 Output: 1

Initialize Counters: cnt is initialized to 0 to keep track of the number of nodes processed so far. res is initialized to Integer.MAX_VALUE to store the k-th smallest element once it is found. In-Order DFS Traversal: Perform a Depth-First Search (DFS) in-order traversal of the tree. In-order traversal visits nodes in ascending order for a Binary Search Tree (BST). For each node visited, increment the counter cnt. If cnt equals k, store the current node's value in res. Return Result: After the traversal, return the value stored in res which is the k-th smallest element. Time Complexity: The time complexity is O(N) in the worst case where N is the number of nodes in the tree. This is because we might need to visit all nodes in the worst-case scenario. Space Complexity: The space complexity is O(H) where H is the height of the tree due to the recursion stack. In the worst case (unbalanced tree), the space complexity can be O(N).

1122 Relative Sort Array Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order. Example 1: Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] Output: [2,2,2,1,4,3,3,9,6,7,19]

Initialize Counting Array: Create an array count of size 1001 to keep track of the frequency of each element in arr1. Initialize an index variable k to 0 for filling the result array res. Count Elements in arr1: Traverse through arr1 and increment the corresponding index in the count array for each element. Place Elements from arr2: Traverse through arr2. For each element, add it to res the number of times it appears in arr1 by decrementing its count in the count array. Place Remaining Elements: Traverse through the count array. For each non-zero value, add the corresponding index to res the number of times it appears in arr1. Return Result: Return the res array which now contains the sorted elements. Time Complexity: O(n + m): where n is the length of arr1 and m is the length of arr2.Counting elements in arr1 takes O(n).Placing elements from arr2 takes O(m).Placing remaining elements takes O(1001) since the count array has a fixed size. Space Complexity: O(1): The count array has a fixed size of 1001, independent of the input size.

79 Word Search Given an m x n grid of characters board and a string word, return true if word exists in the grid. Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" Output: true

Initialize Dimensions and Visited Array: Get the dimensions m (number of rows) and n (number of columns) from the board. Create a visited array to keep track of visited cells to avoid cycles. Iterate Through Each Cell: Iterate through each cell of the board. If a cell matches the first character of the word, initiate a depth-first search (DFS) from that cell. DFS Helper Function: Base Case: If the index matches the length of the word, it means all characters have been matched, so return true. Mark the current cell as visited. Explore all 4 possible directions (up, down, left, right) from the current cell. For each direction, calculate the next cell coordinates. Check boundary conditions, if the next cell is already visited, or if the character in the next cell does not match the current character in the word, continue to the next direction. If a valid path is found from any direction, return true. Unmark the current cell as visited (backtrack). If no valid path is found from the current cell, return false. Return Result: If any DFS initiated from any cell returns true, return true. If all DFS attempts fail, return false. Time Complexity: O(m * n * 4^L): Where m is the number of rows, n is the number of columns, and L is the length of the word. This is because each cell can initiate a DFS and each DFS can branch in 4 directions up to the length of the word. Space Complexity: O(m * n): For the visited array and recursion stack space.

387 First Unique Character in a String Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1. Input: s = "leetcode" Output: 0

Initialize Frequency Array: Create an array freq of size 26 to store the frequency of each character in the string s. First Pass - Count Frequencies: Iterate through the string s and update the frequency array freq for each character. Second Pass - Find First Unique Character: Iterate through the string s again. Check the frequency of each character using the freq array. Return the index of the first character that has a frequency of 1. Return Result: If no unique character is found, return -1. Time Complexity: O(n): The algorithm iterates through the string s twice, where n is the length of the string. Space Complexity: O(1): The size of the frequency array freq is fixed at 26, which is constant space.

797 All Paths From Source to Target Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order. 回溯 三个问题 1. 路径 2. 选择列表 3. 结束条件 backtracking(路径,选择列表){ if(满足结束条件){ res.add(路径); return; } for(选择: 选择列表){ 做选择 backtracking(路径,选择列表); 撤销选择}}

Initialize Result List: Create a list res to store all valid paths from the source to the target. Initialize Path List: Create a list path to keep track of the current path being explored. Start with the source node (0) and add it to path. Backtracking Function: Recursively explore all possible paths from the current node to the target node. If the current node is the target node, add the current path to the result list. For each neighbor of the current node:Add the neighbor to the current path.Recursively call the backtracking function with the neighbor as the new current node.Remove the last node from the current path to backtrack and explore other paths. Time Complexity: O(2^N * N): There can be up to 2N2^N2N paths in the graph, each taking O(N)O(N)O(N) time to process. O(N) per path: Each path can be of length NNN. Space Complexity: O(N): For the recursion stack and the current path list.

1002 Find Common Characters 给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。 输入:words = ["bella","label","roller"] 输出:["e","l","l"]

Initialize Result List: Create a list result to store common characters. Check for Empty Input: If the input array A is empty, return the empty result list. Initialize Frequency Array: Create an array hash of size 26 to store the minimum frequency of each character ('a' to 'z') across all strings. Initialize this array using the first string in the array. Update Frequency for Each String: For each subsequent string in the array:Create a temporary frequency array hashOtherStr to count the frequency of each character in the current string.Update the hash array to keep track of the minimum frequency of each character seen so far. Convert Frequency Array to Result List: For each character in the hash array:Add the character to the result list as many times as its frequency in hash. Return Result: Return the result list containing the common characters. Time Complexity: O(N * M):N is the number of strings in the array A.M is the average length of the strings.The algorithm iterates through each character of each string, making it O(N * M). Space Complexity: O(26) = O(1):The size of the frequency arrays (hash and hashOtherStr) is fixed at 26, which is constant space.The result list space is proportional to the number of common characters, but this is typically much smaller than the input size, so it can be considered O(1).

53 Maximum Subarray Given an integer array nums, find the subarray with the largest sum, and return its sum. Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: The subarray [4,-1,2,1] has the largest sum 6.

Initialize Result and DP Array: Create an integer variable res to store the maximum subarray sum found so far and initialize it with the first element of the nums array. Create a dp array of the same length as nums to store the maximum subarray sum ending at each index. Dynamic Programming Initialization: Initialize the first element of the dp array with the first element of the nums array. Iterate Through the Array: For each element in nums starting from the second element:Update the dp array at the current index with the maximum of:The sum of the current element and the maximum subarray sum ending at the previous index (dp[i - 1] + nums[i]).The current element itself (nums[i]).Update res with the maximum value between res and the current dp value. dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]); res = Math.max(res, dp[i]); Return Result: Return the value of res, which contains the maximum subarray sum. Time Complexity: O(n): The algorithm iterates through the nums array once, performing constant-time operations for each element. Space Complexity: O(n): The dp array stores the maximum subarray sum ending at each index.

410 Split Array Largest Sum Given an integer array nums and an integer k, split nums into k non-empty subarrays such that the largest sum of any subarray is minimized. Return the minimized largest sum of the split. 输入:nums = [7,2,5,10,8], k = 2 输出:18 解释: 一共有四种方法将 nums 分割为 2 个子数组。 其中最好的方式是将其分为 [7,2,5] 和 [10,8] 。 因为此时这两个子数组各自的和的最大值为18,在所有情况中最小。

Initialize Search Boundaries: Set start to the maximum element in nums since the largest subarray sum must be at least the largest element. Set end to the sum of all elements in nums since this represents the scenario where there is only one subarray containing all elements. Binary Search: Use binary search to narrow down the smallest possible maximum subarray sum. While start and end are not close enough (start + 1 < end):Compute mid as the middle point between start and end.Use getC to determine the number of subarrays needed if the maximum allowed sum is mid.If the number of subarrays is less than or equal to m, it means we can reduce the maximum sum, so set end to mid.Otherwise, set start to mid. Return the Result: After the binary search loop, check if start can be the answer by calling getC. If it returns a value less than or equal to m, return start. Otherwise, return end. Time Complexity: The binary search runs in O(log(sum of nums)) time, where the sum of nums is the range of possible values for the maximum subarray sum. The getC function runs in O(n) time, where n is the length of nums. Overall time complexity is O(n * log(sum of nums)). Space Complexity: The space complexity is O(1) since we are using only a few extra variables.

187 Repeated DNA Sequences Given a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order. Example 1: Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" Output: ["AAAAACCCCC","CCCCCAAAAA"]

Initialize Variables: Create a list ans to store the repeated DNA sequences. Get the length n of the input string s. Create a HashMap map to store the count of each 10-letter substring. Iterate Through the String: Use a for loop to iterate through the string, considering each 10-letter substring. For each substring, check its count in the map. If the count is exactly 1, add the substring to the result list ans. Update the count of the substring in the map. Return Result: Return the list ans containing all repeated DNA sequences. Time Complexity: O(n): The algorithm iterates through the string s once, where n is the length of the string. Each substring operation and HashMap operation is O(1) on average. Space Complexity: O(n): The HashMap stores up to n-9 substrings, where each substring is of fixed length 10. The result list ans can store at most n-9 repeated substrings.

658 Find K Closest Elements Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order. 整数 a 比整数 b 更接近 x 需要满足: |a - x| < |b - x| 或者 |a - x| == |b - x| 且 a < b 示例 1: 输入:arr = [1,2,3,4,5], k = 4, x = 3 输出:[1,2,3,4]

Initialize Variables: Create a list res to store the k closest elements. Initialize start to 0 and end to arr.length - k to define the search range for the leftmost index of the k closest elements. Binary Search to Find the Starting Index: Use a while loop to perform binary search within the range [start, end]. Calculate the midpoint mid of the current range. Compare the difference between x and arr[mid] with the difference between arr[mid + k] and x to decide whether to move the start or end pointer. If x > arr[mid] and x - arr[mid] > arr[mid + k] - x, update start to mid + 1 because the k elements starting from mid + 1 are closer to x than those starting from mid. Otherwise, update end to mid to include the current mid in the search range. Collect the k Closest Elements: After finding the starting index start, iterate from start to start + k and add the elements to the result list res. Return the Result: Return the list res containing the k closest elements. Time Complexity: O(log(n - k) + k): The binary search takes O(log(n - k)) time and collecting the k elements takes O(k) time. Space Complexity: O(k): The space complexity is O(k) for storing the k closest elements in the result list.

691 Stickers to Spell Word 我们有 n 种不同的贴纸。每个贴纸上都有一个小写的英文单词。 您想要拼写出给定的字符串 target ,方法是从收集的贴纸中切割单个字母并重新排列它们。如果你愿意,你可以多次使用每个贴纸,每个贴纸的数量是无限的。 Return the minimum number of stickers that you need to spell out target. If the task is impossible, return -1. Example 1: Input: stickers = ["with","example","science"], target = "thehat" Output: 3 Explanation: We can use 2 "with" stickers, and 1 "example" sticker. After cutting and rearrange the letters of those stickers, we can form the target "thehat".

Initialize Variables: Create a set targetSet to store unique characters in the target string. Create a list availables to store the counts of relevant characters in each sticker. Filter and Count Stickers: For each sticker in stickers, get the character count map using getCounter method. Add the count map to availables if it contains any characters from the target. Breadth-First Search (BFS): Use a deque queue to perform BFS starting with the target. Use a map cost to keep track of the minimum stickers needed to form each state. While the queue is not empty, process each state:For each available sticker map:Check if the sticker can be used to reduce the current state.Generate the next state using nextState method.If the next state is empty, return the current cost plus one.If the next state has not been visited, add it to the queue and update its cost. Helper Methods: getCounter(String s, Set<Character> chars): Returns a map of character counts for characters in chars. nextState(String s, Map<Character, Integer> map): Generates the next state by applying the sticker count map to the current state string. Return Result: If BFS completes without finding a solution, return -1. Time Complexity: O(n * m * t): Where n is the number of stickers, m is the average length of stickers, and t is the length of the target string. BFS traversal and state generation are the primary contributors to the complexity. Space Complexity: O(m * 2^t): For storing the cost map and queue states, where t is the length of the target string.

1347 Minimum Number of Steps to Make Two Strings Anagram You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character. Return the minimum number of steps to make t an anagram of s. Input: s = "bab", t = "aba" Output: 1 Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s.

Initialize Variables: Use an array freq of size 26 to count the frequency of each character in s. Initialize res to store the number of steps required to make t an anagram of s. Count Frequencies in s: Iterate through each character in s and update the freq array to count the frequency of each character. Count Steps to Adjust t: Iterate through each character in t:If the character exists in the freq array with a count greater than 0, decrement the count.If the character does not exist in the freq array or its count is 0, increment res (indicating a step needed to change or add this character). Return the Result: Return the value of res, which represents the minimum steps required to make t an anagram of s. Time Complexity: O(n): Where n is the length of the strings s and t. Each character in both strings is processed once. Space Complexity: O(1): The space complexity is constant as the freq array size is fixed at 26.

513 Find Bottom Left Tree Value Given the root of a binary tree, return the leftmost value in the last row of the tree. DFS 同理,可以使用 DFS 进行树的遍历,每次优先 DFS 当前节点的左子树,每次第一次搜索到当前深度 depth 时,必然是当前深度的最左节点,此时用当前节点值来更新 ans。

Initialize Variables: Use max to keep track of the maximum depth encountered. Use ans to store the value of the leftmost node at the maximum depth. Depth-First Search (DFS): Start the DFS from the root with an initial depth of 1. If the current node is null, return immediately. If the current depth is greater than the maximum depth encountered so far, update max and ans to the current depth and node value, respectively. Recursively call DFS on the left child first (to ensure the leftmost node is prioritized) and then on the right child, incrementing the depth by 1 for each recursive call. Return the Result: After completing the DFS traversal, ans will hold the value of the bottom-left node. Time Complexity: O(n): Each node is visited once, where n is the number of nodes in the tree. Space Complexity: O(h): The space complexity is determined by the height h of the tree due to the recursion stack.

409 Longest Palindrome Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive, for example, "Aa" is not considered a palindrome. Example 1: Input: s = "abccccdd" Output: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.

Initialize Variables: ans to store the length of the longest palindrome. hasMid to indicate if there's a character with an odd count. map to count the frequency of each character in the string s. Count Character Frequencies: Traverse through the string s, and for each character, update its frequency in the map. Calculate Longest Palindrome Length: Traverse through the values in the map. For each value v, add it to ans. If v is odd, subtract 1 from ans and set hasMid to true. Adjust for Odd Frequency Characters: If hasMid is true, add 1 to ans to account for the middle character in the palindrome. Return Result: Return ans as the length of the longest palindrome that can be built. Time Complexity: O(n): where n is the length of the string s.Counting frequencies takes O(n).Traversing the values in the map takes O(1) because there are at most 26 different lowercase letters. Space Complexity: O(1): The map stores at most 26 entries (for lowercase English letters), making the space complexity constant.

390 Elimination Game You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr: 从左到右,删除第一个数字,然后每隔一个数字删除一个,直到到达列表末尾。 重复上面的步骤,但这次是从右到左。也就是,删除最右侧的数字,然后剩下的数字每隔一个删除一个。 不断重复这两步,从左到右和从右到左交替进行,直到只剩下一个数字。 Given the integer n, return the last number that remains in arr. Input: n = 9 Output: 6 Explanation: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] arr = [2, 4, 6, 8] arr = [2, 6] arr = [6]

Initialize Variables: head to keep track of the first element in the current sequence. step to keep track of the step size for each iteration. left to determine the direction of removal (starting from left or right). n to keep track of the number of remaining elements. Iterate Until Only One Element Remains: Use a while loop that continues until n is greater than 1. If the removal is from the left (left == true) or from the right when the number of elements (n) is odd, update the head by adding the step. Double the step size after each iteration. Toggle the left flag to switch the direction of removal. Halve the number of elements (n) after each iteration. Return the Last Remaining Element: After the loop, head will point to the last remaining element. Time Complexity: O(log n): The number of iterations is proportional to the number of times n can be halved, which is logarithmic. Space Complexity: O(1): The algorithm uses a constant amount of space.

169 Majority Element Given an array nums of size n, return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times.

Initialize Variables: major: To keep track of the current candidate for the majority element. vote: To keep track of the number of votes for the current candidate. Iterate Through the Array: For each element num in the array A:If cnt is 0, set major to num and increment vote.If num is equal to major, increment cnt.If num is not equal to major, decrement cnt . Return Result: After the loop completes, major will contain the majority element. Time Complexity: O(n): The function iterates through each element in the array exactly once, where n is the length of the array. Space Complexity: O(1): The space complexity is constant as only a fixed amount of extra space is used, regardless of the input size.

1614 Maximum Nesting Depth of the Parentheses Given a valid parentheses string s, return the nesting depth of s. The nesting depth is the maximum number of nested parentheses. 输入:s = "(1+(2*3)+((8)/4))+1" 输出:3 解释:数字 8 在嵌套的 3 层括号中。

Initialize Variables: max: To keep track of the maximum depth of nested parentheses. left: To keep track of the current depth of nested parentheses as we traverse the string. Iterate Through the String: Use a for loop to iterate through each character in the string s. If the current character cur is '(', increment left to indicate an increase in the current depth. Update max to be the maximum of the current max and left. If the current character cur is ')', decrement left to indicate a decrease in the current depth. Return the Result: Return the value of max, which represents the maximum depth of nested parentheses. Time Complexity: O(n): The function iterates through each character in the string exactly once, where n is the length of the string. Space Complexity: O(1): The space complexity is O(1) as only a constant amount of extra space is used.

877 Stone Game Alice 和 Bob 用几堆石子在做游戏。一共有偶数堆石子,排成一行;每堆都有 正 整数颗石子,数目为 piles[i] 。 游戏以谁手中的石子最多来决出胜负。石子的 总数 是 奇数 ,所以没有平局。 Alice 和 Bob 轮流进行,Alice 先开始 。 每回合,玩家从行的 开始 或 结束 处取走整堆石头。 这种情况一直持续到没有更多的石子堆为止,此时手中 石子最多 的玩家 获胜 。 假设 Alice 和 Bob 都发挥出最佳水平,当 Alice 赢得比赛时返回 true ,当 Bob 赢得比赛时返回 false 。

Initialize Variables: n to store the length of the piles array. f array of size n to store the maximum difference of stones that the player can achieve from a given range of piles. Dynamic Programming Approach: Iterate over all possible lengths of subarrays (l from 2 to n). For each length, iterate over all possible starting points (i). Calculate the maximum difference of stones the player can achieve for each subarray using the formula:f[i] = Math.max(piles[i] - f[i + 1], piles[i + l - 1] - f[i])This formula considers both possible moves: taking the first pile or the last pile in the current subarray. Return Result: If f[0] is greater than 0, it means the player starting the game can get more stones than the opponent, thus return true. Time Complexity: O(n^2): Two nested loops where both run up to n. Space Complexity: O(n): For the f array.

907 Sum of Subarray Minimums Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 10^9 + 7. Input: arr = [3,1,2,4] Output: 17 Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17.

Initialize Variables: res to store the result. n as the length of the array A. mod to store the modulus value 109+710^9 + 7109+7. left and right arrays to store the number of contiguous subarrays in which A[i] is the minimum, extending to the left and right respectively. Two stacks s1 and s2 to help in computing the left and right arrays. Calculate left Array: Traverse the array from left to right. Use stack s1 to keep track of elements and their counts. For each element A[i], calculate how many subarrays end at i where A[i] is the minimum. Push the current element and its count onto the stack. Calculate right Array: Traverse the array from right to left. Use stack s2 to keep track of elements and their counts. For each element A[i], calculate how many subarrays start at i where A[i] is the minimum. Push the current element and its count onto the stack. Calculate the Result: For each element A[i], the number of subarrays where A[i] is the minimum is left[i] * right[i]. Multiply this count by A[i] and add to res modulo mod. Return the Result: Return the final value of res. Time Complexity: O(n): Each element is processed a constant number of times, leading to linear time complexity. Space Complexity: O(n): Additional space is used for the left, right arrays and the stacks.

2385 Amount of Time for Binary Tree to Be Infected Input: root = [1,5,3,null,4,10,6,9,2], start = 3 Output: 4 Explanation: The following nodes are infected during: - Minute 0: Node 3 - Minute 1: Nodes 1, 10 and 6 - Minute 2: Node 5 - Minute 3: Node 4 - Minute 4: Nodes 9 and 2

Initialize Variables: startNode to keep track of the starting node. fa (a map) to store the parent of each node. DFS to Populate Parent Pointers and Find Start Node: Traverse the tree using DFS. For each node, record its parent. Identify and store the node with the start value. Modified DFS to Calculate Maximum Depth: Start DFS from the start node. For each node, recursively calculate the depth by considering moves to the left child, right child, and parent. Track the maximum depth encountered during the traversal. Time Complexity: O(n): Each node is visited once during the DFS traversals. Space Complexity: O(n): Space for the map to store parent pointers and the recursion stack.

134 Gas Station Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2] Output: 3

Initialize Variables: sum: To keep track of the current running balance of gas minus cost. total: To keep track of the total balance of gas minus cost across all stations. start: To keep track of the potential starting station index. Iterate Through Gas Stations: Loop through each gas station:Update total and sum by adding the difference between the gas available at the station and the cost to reach the next station.If sum becomes negative:This means that starting from the current start station cannot complete the circuit.Update start to the next station (i + 1).Reset sum to 0 to start calculating the balance from the next station. Determine the Result: After completing the loop, check the total balance. If total is negative, return -1 indicating that it is not possible to complete the circuit starting from any station. Otherwise, return start as the starting station index. Time Complexity: O(n): The algorithm processes each gas station exactly once, where n is the number of gas stations. Space Complexity: O(1): The algorithm uses a fixed amount of additional space for variables (sum, total, and start).

875 Koko Eating Bananas 珂珂喜欢吃香蕉。这里有 n 堆香蕉,第 i 堆中有 piles[i] 根香蕉。警卫已经离开了,将在 h 小时后回来。 珂珂可以决定她吃香蕉的速度 k 。每个小时,她将会选择一堆香蕉,从中吃掉 k 根。如果这堆香蕉少于 k 根,她将吃掉这堆的所有香蕉,然后这一小时内不会再吃更多的香蕉。 Return the minimum integer k such that she can eat all the bananas within h hours.

Initialize the Binary Search Bounds: Set the lower bound lo to 1. Set the upper bound hi to the maximum pile size in the array piles. Binary Search for the Minimum Eating Speed: Use binary search to find the smallest value of K such that all the bananas can be eaten within H hours. Calculate the middle point K as lo + ((hi - lo) >> 1). Check if it is possible to eat all bananas with the current K using the helper function canEatAll. If it is possible, adjust the upper bound hi to K. If it is not possible, adjust the lower bound lo to K. Helper Function canEatAll: Iterate through each pile in piles. Calculate the total hours needed to eat all bananas at speed K. If the total hours exceed H, return false. Otherwise, return true. Helper Function getMaxPile: Iterate through each pile in piles. Track and return the maximum pile size. Time Complexity: The time complexity of the solution is O(N log M), where N is the number of piles and M is the size of the largest pile. This is because the binary search runs in O(log M) time and for each iteration of the binary search, we need to check all N piles. Space Complexity: The space complexity is O(1) as we are using a constant amount of extra space.

513 Find Bottom Left Tree Value Given the root of a binary tree, return the leftmost value in the last row of the tree. Input: root = [2,1,3] Output: 1 BFS 使用 BFS 进行「层序遍历」,每次用当前层的首个节点来更新 ans,当 BFS 结束后,ans 存储的是最后一层最靠左的节点。

Initialize the Queue: Use a Queue<TreeNode> to facilitate a level-order traversal (BFS) of the tree. Add the root node to the queue. Traverse the Tree Level by Level: While the queue is not empty:Determine the number of nodes at the current level (size).Update the result (res) to the value of the first node at the current level (the leftmost node).For each node at the current level:Remove the node from the queue.Add its left child to the queue (if it exists).Add its right child to the queue (if it exists). Return the Result: After completing the level-order traversal, res will hold the value of the bottom-left node of the tree. Time Complexity: O(n): Each node is visited once, where n is the number of nodes in the tree. Space Complexity: O(w): The space complexity is determined by the maximum width w of the tree, which is the maximum number of nodes at any level of the tree.

197 Rising Temperature Write a solution to find all dates' Id with higher temperatures compared to its previous dates (yesterday). Return the result table in any order.

SELECT t.IdFROM Weather AS t,Weather AS yWHERE DATEDIFF(t.RecordDate, y.RecordDate) = 1AND t.Temperature > y.Temperature;

2971 Find Polygon With the Largest Perimeter 找到最大周长的多边形 多边形 指的是一个至少有 3 条边的封闭二维图形。多边形的 最长边 一定 小于 所有其他边长度之和。一个多边形的 周长 指的是它所有边之和。 Return the largest possible perimeter of a polygon whose sides can be formed from nums, or -1 if it is not possible to create a polygon.

Sort the Array: First, sort the array in non-decreasing order. Check Triangle Inequality: Iterate from the end of the array to the start, considering three consecutive numbers at a time. Check if these three numbers satisfy the triangle inequality condition (i.e., the sum of the two smaller numbers is greater than the largest number). Return the Largest Perimeter: If a valid triangle is found, return the perimeter of that triangle. If no valid triangle can be formed, return 0. Explanation: The triangle inequality theorem states that for any three sides to form a triangle, the sum of any two sides must be greater than the third side. By sorting the array and then iterating from the largest numbers to the smallest, we can quickly find the largest possible perimeter. Time Complexity: O(n log n): Sorting the array. O(n): Iterating through the array to check the triangle condition. Space Complexity: O(1): Only a few additional variables are used.

881 Boats to Save People You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit. Return the minimum number of boats to carry every given person. 输入:people = [3,2,2,1], limit = 3 输出:3 解释:3 艘船分别载 (1, 2), (2) 和 (3)

Sort the Array: Sort the array people to facilitate the pairing of the lightest and heaviest persons. Initialize Variables: solution: To count the minimum number of boats required. start: Pointer to the lightest person (beginning of the array). end: Pointer to the heaviest person (end of the array). Iterate Using Two Pointers: Use a while loop to iterate until start is less than or equal to end. If the sum of the weights of the persons at start and end is less than or equal to the limit, it means both can share a boat. Increment start. Always decrement end to account for the person at end being placed in a boat. Increment solution for each boat used. Return Result: After the loop, solution will contain the minimum number of boats required. Time Complexity: O(n log n): The function sorts the array which takes O(n log n) time. The subsequent iteration through the array takes O(n) time. Space Complexity: O(1): The space complexity is constant as only a fixed amount of extra space is used, regardless of the input size.

90 Subsets II Given an integer array nums that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. Example 1: Input: nums = [1,2,2] Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]

Sort the Array: Sort the input array nums to ensure that duplicates are adjacent. This helps in easily skipping duplicate elements during the DFS traversal. Initialize Result List: Create a result list res to store all subsets. Depth-First Search (DFS) Function: Use a helper function dfs to perform the depth-first search to generate subsets. Parameters of DFS:res: The result list to store subsets.path: The current subset being built.nums: The input array.pos: The current position in the array nums from where the next element should be considered. DFS Traversal: Add the current path to the result list res. Loop through the array starting from the current position pos:Skip duplicates by checking if the current element is the same as the previous one.Add the current element to the path.Recursively call the dfs function to continue building the subset from the next position.Remove the last element from the path to backtrack and try other possibilities. Time Complexity: O(2^n): Each element can either be included or excluded from a subset, leading to 2n2^n2n possible subsets. Sorting the array takes O(nlog⁡n)O(n \log n)O(nlogn), but the dominant factor is O(2n)O(2^n)O(2n). Space Complexity: O(n): The depth of the recursion tree can go up to the length of the array nnn, and each subset can be of length nnn in the worst case.

165 Compare Version Numbers Given two version strings, version1 and version2, compare them. A version string consists of revisions separated by dots '.'. The value of the revision is its integer conversion ignoring leading zeros. Return the following: If version1 < version2, return -1. If version1 > version2, return 1. Otherwise, return 0. 示例 1: 输入:version1 = "1.2", version2 = "1.10" 输出:-1 解释: version1 的第二个修订号为 "2",version2 的第二个修订号为 "10":2 < 10,所以 version1 < version2。 示例 2: 输入:version1 = "1.01", version2 = "1.001" 输出:0 解释: 忽略前导零,"01" 和 "001" 都代表相同的整数 "1"。 示例 3: 输入:version1 = "1.0", version2 = "1.0.0.0" 输出:0 解释: version1 有更少的修订号,每个缺失的修订号按 "0" 处理。

Split Versions into Components: Split both version1 and version2 strings by the dot . character into arrays v1 and v2. Determine the Maximum Length: Calculate the maximum length n of the two version arrays v1 and v2. Iterate and Compare: Loop through each index i from 0 to n - 1. For each index i, get the version component from v1 and v2, defaulting to 0 if the index is out of bounds. Compare the two components:If the component from v1 is greater than the component from v2, return 1.If the component from v1 is less than the component from v2, return -1.If the components are equal, continue to the next index. Return Result: If all components are equal, return 0. Time Complexity: O(n): The function iterates through the components of the longer version string, where n is the maximum length of the two version strings. Space Complexity: O(n + m): The space complexity is O(n + m) for storing the split version components, where n and m are the lengths of version1 and version2.

629 K Inverse Pairs Array 对于一个整数数组 nums,逆序对是一对满足 0 <= i < j < nums.length 且 nums[i] > nums[j]的整数对 [i, j] 。 给你两个整数 n 和 k,找出所有包含从 1 到 n 的数字,且恰好拥有 k 个 逆序对 的不同的数组的个数。由于答案可能很大,只需要返回对 10^9 + 7 取余的结果。 输入:n = 3, k = 1 输出:2 解释: 数组 [1,3,2] 和 [2,1,3] 都有 1 个逆序对。 3,2,1 有三个逆序对

https://leetcode.cn/problems/k-inverse-pairs-array/solutions/1095887/629-kge-ni-xu-dui-shu-zu-dong-tai-gui-hu-qxyt/

642 Design Search Autocomplete System Implement the AutocompleteSystem class: AutocompleteSystem(String[] sentences, int[] times) Initializes the object with the sentences and times arrays. List<String> input(char c) This indicates that the user typed the character c. Returns an empty array [] if c == '#' and stores the inputted sentence in the system. Returns the top 3 historical hot sentences that have the same prefix as the part of the sentence already typed. If there are fewer than 3 matches, return them all.

TrieNode Class: Define a nested TrieNode class that contains:A map children to store child nodes for each character.A map counts to store the frequency of sentences.A boolean isWord to mark the end of a word. AutocompleteSystem Constructor: Initialize the root node of the trie and an empty prefix string. Populate the trie by calling the add method for each sentence in the input array with their corresponding times. Add Method: Traverse the trie for each character in the sentence. If a child node does not exist for a character, create a new TrieNode. Update the counts map to reflect the frequency of the sentence. Mark the node as a word if the end of the sentence is reached. Input Method: Handle the special character # to indicate the end of input:Add the current prefix to the trie with a count of 1.Reset the prefix and return an empty list. Append the input character to the prefix. Traverse the trie based on the updated prefix:If a character does not exist in the trie, return an empty list. Use a priority queue to find the top 3 sentences with the highest frequency:Sort by frequency (descending) and then lexicographically (ascending). Extract the top 3 results from the priority queue and return them. Time Complexity: O(n): For adding sentences to the trie where n is the length of the sentence. O(p + m log m): For processing each input character, where p is the length of the prefix and m is the number of sentences starting with the prefix (due to the priority queue operations). Space Complexity: O(n): Space for the trie nodes and the frequency map, where n is the total number of characters in all sentences.


Ensembles d'études connexes

ECON 2030; CH. 12: Aggregate Expenditure and Output in the Short Run

View Set

Psychology Exam 1 Multiple Choice

View Set

Texas Principles of Real Estate 1 - Chapter 5

View Set

Acctg 432 Exam 1: Revenue Cycle Flowchart

View Set

Medication Administration Test - Dosage Calculation and Safe Medication Administration 3.0

View Set

business short questions 2015-2007

View Set

Dynamics of Addiction Exam 1 Study

View Set