current position:Home>Java lesson 30

Java lesson 30

2022-04-29 06:11:00Yake1965

1897. Reassign characters so that all strings are equal

Basic knowledge of

The first 30 course

1331. Array number conversion

1002. Find common characters

Basic knowledge of

The first 31 course

914. Card groups

904. Fruit baskets

781. Rabbits in the forest

class Solution:
    def numRabbits(self, answers: List[int]) -> int:
        n, ans = len(answers), 0
        cnt = Counter(answers)
        for k, v in cnt.items():
            ans += (v + k) // (k + 1) * (k + 1)
            #ans += ceil(v/(k+1)) * (k + 1)
        return ans
class Solution {
    
    public int numRabbits(int[] answers) {
    
        int ans = 0;
        Map<Integer, Integer> map = new HashMap<>();
        for (int x : answers) 
            map.put(x, map.getOrDefault(x, 0) + 1);
       
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    
            int k = entry.getKey(), v =  entry.getValue();
            ans += (k + v) / (k + 1) * (k + 1);
        }
  
        return ans;
    }
}

Basic knowledge of

The first 32 course

648. Word substitution

class Solution:
    def replaceWords(self, dictionary: List[str], sentence: str) -> str:
        word = sentence.split()
        d = set(dictionary)
        ans = []
        for w in word:           
            for i in range(len(w)):
                s = w[:i+1]
                if s in d:
                    ans.append(w[:i+1])
                    break
            else: ans.append(w)
        return ' '.join(ans)
class Solution {
    
    public String replaceWords(List<String> dictionary, String sentence) {
    
        String[] t = sentence.split(" ");
        List<String> ans = new ArrayList<>();
        Set<String> d = new HashSet(dictionary);
        sign:
        for (String w : t){
    
            for (int i = 0; i < w.length(); i++){
    
                String x = w.substring(0, i+1);
                if (d.contains(x)){
    
                    ans.add(x);
                    continue sign;
                }                
            }
            ans.add(w);
        }
        String s = String.join(" ", ans);
        return s;
    }
}

389. Make a difference

*1700. Number of students unable to have lunch

Basic knowledge of

The first 33 course

229. Find mode II

1365. How many numbers are smaller than the current number

888. Fair candy exchange

1452. Collection list

Basic knowledge of

The first 34 course

383. Ransom letter

997. Find the judge in town

229. Find mode II

575. Divide candy

1054. Bar codes with equal distances

class Solution:
    def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
        d, n = Counter(barcodes), len(barcodes)
        ans = [0] * n
        q = sorted(d.items(), key=lambda x:x[1])
        i = 0
        for k, v in reversed(q):
            for _ in range(v):
                ans[i] = k
                i += 2
                if i >= n: i = 1        
        return ans
class Solution {
    
    public int[] rearrangeBarcodes(int[] barcodes) {
    
        Map<Integer, Integer> map = new HashMap<>();
        for (int b : barcodes) {
    
            map.put(b, map.getOrDefault(b, 0) + 1);
        }
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> (b[1] - a[1]));
        for (int k : map.keySet()) {
    
            pq.add(new int[]{
    k, map.get(k)});
        }
        int[] res = new int[barcodes.length];
        int i = 0;
        while (!pq.isEmpty()) {
    
            int[] temp = pq.poll();
            while (temp[1] -- > 0) {
    
                res[i] = temp[0];
                i += 2;
                if (i >= barcodes.length) i = 1;
            }            
        }
        return res;
    }
}

560. And for K Subarray

class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        res, acc, d = 0, 0, {
    }
        for x in nums:
            d[acc] = d.get(acc, 0) + 1
            acc += x
            res += d.get(acc - k, 0)
        return res
class Solution {
    
    public int subarraySum(int[] nums, int k) {
    
        int res = 0, acc = 0;
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++){
    
            map.put(acc, map.getOrDefault(acc, 0) + 1);
            acc += nums[i];
            res += map.getOrDefault(acc - k, 0);            
        }
        return res;
    }
}

41. First positive number missing

class Solution:
    def firstMissingPositive(self, nums: List[int]) -> int:        
        n = len(nums)
        m = n + 1
        #  Preprocessing negative numbers  >n  Number of numbers 
        for i in range(n):
            x = nums[i]
            if x > n or x < 0:
                nums[i] = 0
        #  Mark  + m
        for i in range(n):
            x = nums[i] % m #  Restore 
            if x > 0: nums[x-1] += m
        for i in range(n):
            if nums[i] < m: return i+1
        return m

242. Effective alphabetic words

244. The shortest word distance II

246. Centrosymmetric number

249. Shift string grouping

264. Ugly number II

266. Palindrome arrangement

267. Palindrome arrangement II

268. Missing numbers

76. Minimum cover substring

288. The only abbreviation of a word

290. Rules of words

class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        words = s.split()
        d = {
    }
        if len(words) != len(pattern):return False
        for i, c in enumerate(pattern):
            w = words[i]
            if c not in d: d[c] = w
            elif d[c] != w: return False                
        if len(d) != len(set(words)): return False
        return True

291. Rules of words II

299. Guess the number game

3. Longest substring without repeating characters

30. Concatenate the substrings of all words

311. Multiplication of sparse matrices

313. Super ugly number

314. Vertical traversal of binary trees

325. And equal to k The longest subarray length of

336. The palindrome is right

340. At most K Longest substring of different characters

347. front K High frequency elements

348. Design tic tac toe chess

349. Intersection of two arrays

350. Intersection of two arrays II

355. Design twitter

356. Line mirror image

358. K The distance interval rearranges the string

359. Log rate limiter

36. Effective Sudoku

362. Hit the counter

379. Telephone directory management system

380. O(1) Time insertion 、 Delete and get random elements

381. O(1) Time insertion 、 Delete and get random elements - Allow repetition

387. The first unique character in the string

395. There are at least K The longest substring of repeated characters

398. Random number index

409. Longest palindrome

421. The maximum exclusive or value of two numbers in an array

423. Reconstructing Chinese from English

424. The longest repeated character after replacement

432. whole O(1) Data structure of

433. Minimal genetic change

438. Find all alphabetic words in the string

442. Duplicate data in array

447. The number of boomerangs

448. Find all the missing numbers in the array

451. Sort the characters according to their frequency of occurrence

454. Add four numbers II

457. Whether there is a loop in the ring array

460. LFU cache

480. Sliding window median

49. Letter heterotopic word grouping

491. Increasing subsequence

496. Next bigger element I

500. Keyboard line

508. The most frequent sub tree elements and

519. Random flip matrix

522. The longest special sequence II

523. Continuous subarrays and

531. Lonely pixels I

532. Array k-diff Number pair

533. Lonely pixels II

535. TinyURL Encryption and decryption

567. Arrangement of strings

582. Kill the process

588. Design memory file system

594. The longest harmonious subsequence

599. The minimum index sum of two lists

604. Iteratively compress strings

609. Find duplicate files in the system

616. Add bold tags to strings

621. Task scheduler

632. Minimum range

635. Design the log storage system

645. The wrong set

652. Look for duplicate subtrees

653. Sum of two numbers IV - Input BST

659. Split the array into successive subsequences

676. Implement a magic dictionary

677. Key value mapping

690. The importance of employees

692. front K High frequency words

694. The number of different islands

697. The degree of the array

705. Design hash sets

706. Design hash map

710. Random numbers in the blacklist

711. The number of different islands II

720. The longest word in the dictionary

726. The number of atoms

73. Matrix zeroing

734. Sentence similarity

736. Lisp Syntax parsing

737. Sentence similarity II

740. Delete and get points

748. The shortest complement

752. Open the turntable lock

758. Bold words in strings

760. Find the displacement map

763. Division of alphabet

767. Refactoring strings

770. Basic calculator IV

771. Gems and stones

791. Custom string sorting

792. Number of words to match subsequence

804. The only Morse code word

811. Subdomain access count

815. Bus routes

817. Linked list component

819. The most common word

820. Compression coding of words

822. Flip card game

823. Binary trees with factors

859. Intimate string

865. The smallest subtree with all the deepest nodes

868. Binary spacing

873. The length of the longest Fibonacci subsequence

884. Unusual words in two sentences

889. Construct binary tree according to preorder and postorder traversal

890. Find and replace patterns

893. Special equivalent string group

895. Maximum frequency stack

911. Online elections

916. Word subsets

923. Many possibilities of the sum of three

929. Unique email address

930. And the same binary subarray

939. Minimum area rectangle

953. Verification of an alien language dictionary

954. Double pair array

957. N After the day of

961. In length 2N Find duplicates in the array of N Secondary elements

966. Vowel spelling checker

970. Strong integer

974. And can be K A subarray of integers

981. Time based key value storage

982. A triple with a bitwise and zero

987. The vertical traversal of a binary tree

992. K Sub array of different integers

1001. Grid lighting

1002. Find common characters

1010. The total duration can be 60 The song of division

1015. Can be K The smallest integer that is divisible

1027. The longest arithmetic sequence

1036. Escape the maze

1048. The longest string chain

105. Construction of binary trees from traversal sequences of preorder and middle order

106. Construct binary tree from middle order and post order traversal sequence

1072. Flip by column to get the maximum number of equal rows

1074. The sum of the elements is the number of submatrixes of the target value

1086. The average score of the top five subjects

1090. The maximum value affected by the tag

1100. The length is K There is no repetition in the string

1122. Relative sorting of arrays

1123. The closest common ancestor of the deepest leaf node

1124. The longest period of good performance

1128. Number of equivalent domino pairs

1133. Maximum unique number

1138. The path on the letterboard

1146. Snapshot array

1152. Analysis of user's website visiting behavior

1153. String conversion

1160. spell the words

1165. Single keyboard

1166. Designing a file system

1169. Query invalid transactions

1170. Compare the frequency of the smallest letter in a string

1171. Delete consecutive nodes with zero sum from the linked list

1172. Plate stack

1177. Construct palindrome string detection

1178. Guess the riddle

1181. Front and back stitching

1189. “ balloon ” Maximum number of

1198. Find the smallest common element in all rows

12. Integer to Roman number

1202. Exchange elements in a string

1207. Unique occurrences

1213. The intersection of three ordered arrays

1218. The longest definite difference subsequence

1224. Maximum equal frequency

1244. To make the best of the rankings

1248. Statistics 「 Graceful subarray 」

1257. The smallest common area

1258. Synonym sentence

126. The word chain II

1261. Look for elements in the contaminated binary tree

127. The word chain

1275. Find out the winner of tic tac toe

128. The longest continuous sequence

1282. User groups

1296. Divide an array into a set of consecutive numbers

1297. The maximum number of substrings

13. Roman numeral to integer

1311. Get videos your friends have watched

133. Clone map

1331. Array number conversion

1338. Halve the size of the array

1345. Jumping game IV

1346. Check the existence of integers and their multiples

1347. The minimum number of steps to make heterotopic words

1348. Tweet count

1357. every other n A discount for one customer

1358. The number of substrings containing all three characters

1365. How many numbers are smaller than the current number

1366. Rank the team by voting

1370. Up down string

1371. Each vowel contains an even number of times the longest substring

138. Copy list with random pointer

1386. Seating the cinema

139. Word splitting

1394. Find the lucky number in the array

1396. Design the subway system

1399. Count the number of the largest groups

140. Word splitting II

1400. structure K Palindrome strings

141. Circular list

1410. HTML Entity Resolver

1418. Order display form

142. Circular list II

1426. Number elements

1429. The first number

1436. Travel terminal

1442. The number of triples that form two exclusive or equal arrays

1443. The minimum time to collect all the apples on the tree

146. LRU cache

1460. Make two arrays equal by flipping the rotor array

1461. Check whether a string contains all the length of K The binary substring of

1477. Find two non overlapping subarrays whose sum is the target value

1481. The minimum number of different integers

1485. Clone a binary tree with random pointers

1487. Make sure the file name is unique

1488. Avoid flooding

149. The most points on the line

1490. clone N Fork tree

1496. Determine whether the paths intersect

1497. Check whether array pairs can be k to be divisible by

1500. Design document sharing system

1506. find N The root node of the fork tree

1512. A good number of pairs

1519. The number of nodes with the same label in the subtree

1540. K Operations change string

1542. Find the longest favorite substring

1546. The maximum number of non empty subarrays with and as the target value and without overlapping

1554. A string with only one different character

1570. Dot product of two sparse vectors

1577. The square of a number is equal to the method number of the product of two numbers

159. The longest substring containing at most two different characters

1590. Make arrays and can be P to be divisible by

1593. Split the string to maximize the number of unique substrings

160. Intersecting list

1600. The order of succession to the throne

1604. Warn people who use the same employee card more than three times in an hour

1624. The longest substring between two identical characters

1636. Sort the array in ascending order by frequency

1638. Count the number of substrings with only one character difference

1640. Can you join to form an array

1650. The nearest common ancestor of a binary tree III

1656. Design ordered flow

1657. Determine whether two strings are close to

1658. take x Reduced to 0 Minimum operands of

166. Fractions to decimals

1660. Correct binary tree

1674. The minimum number of operations to make arrays complementary

1679. K The maximum number of sum pairs

1684. Count the number of consistent strings

169. Most elements

1695. Delete the maximum score of the subarray

17. Letter combination of telephone number

170. Sum of two numbers III - Data structure design

1711. Big meal count

1713. Get the minimum number of operations of subsequence

1726. Coproduct tuple

1737. The minimum number of characters to be changed to satisfy one of the three conditions

1740. Find the distance in the binary tree

1742. The maximum number of balls in the box

1743. Restore an array from a pair of adjacent elements

1748. The sum of the only elements

1756. Design recently used (MRU) queue

1763. The longest nice substring

1772. Rank functions by popularity

1775. Make the sum of arrays equal by the least number of operations

1781. The sum of all substrings

1790. Can performing only one string exchange make two strings equal

1794. Count the number of substring pairs with the smallest distance

1796. The second largest number in a string

1797. Design a verification system

1804. Realization Trie ( Prefix tree ) II

1805. The number of different integers in a string

1807. Replace the parentheses in the string

1814. Count the number of good pairs in an array

1817. Find user active minutes

1832. Judge whether the sentence is a full letter sentence

1836. Remove duplicate elements from the unsorted linked list

1852. The number of types of numbers in each subarray

1857. The maximum color value in a directed graph

1865. Find the subscript pair for the specified value

187. Repetitive DNA Sequence

1876. Substrings of three different characters

1893. Check that all integers in the region are overwritten

1897. Reassign characters so that all strings are equal

1906. The minimum value of the absolute value of the query difference

1912. Design movie rental system

1915. The number of most beautiful substrings

1930. The length is 3 Different palindrome subsequences

1932. Merge multiple binary search trees

1935. The maximum number of words that can be entered

1940. Sort the longest common subsequence between arrays

1941. Check that all characters appear the same number of times

1948. Delete duplicate folders in the system

1993. Operations on the tree

2001. Number of groups of interchangeable rectangles

2006. The absolute value of the difference is K Number to number

2007. Restore the original array from the double array

2013. Detection square

202. Happy number

2025. The maximum number of schemes to split the array

2032. Values that appear in at least two arrays

2034. Stock prices fluctuate

2043. Simple banking system

205. Isomorphic Strings

2053. No K A unique string

2062. Count the vowel substrings in the string

2068. Check that the two strings are almost equal

208. Realization Trie ( Prefix tree )

2080. The frequency of querying numbers in the interval

2083. Find the total number of substrings beginning and ending with the same letter

2085. Count the public strings that appear once

2094. find 3 Bit even

2099. Find and the maximum length is K The subsequence

2103. Ring and rod

2107. Share K The number of unique flavors after a candy

2115. Find all the dishes you can make from a given raw material

2121. The sum of the intervals of the same elements

2122. Restore the original array

2131. The longest palindrome string obtained by connecting two letter words

2133. Check whether each row and column contains all integers

2135. Count the number of words you can get by adding letters

2150. Find all the numbers in the array

2152. The minimum number of lines required to pass through all points

2154. Multiply the found value by 2

2166. Design bit set

2168. The number of unique substrings with the same frequency for each number

217. There are duplicate elements

2170. The minimum number of operands to make an array an alternating array

2186. The minimum number of steps to make two strings into alphabetic ectopic words

219. There are duplicate elements II

2190. Immediately following in the array key Then the most frequent number

2196. Create a binary tree according to the description

2201. Statistics of the artifacts that can be extracted

2206. Divide the array into equal pairs

2215. Find out the difference between the two arrays

2225. Find the player who lost zero or one game

2227. Encrypt and decrypt strings

2244. The minimum number of rounds required to complete all tasks

copyright notice
author[Yake1965],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/116/202204261000558716.html

Random recommended