Test Exercises
Output of keyboard with keys 1 and 5
There is a special 5-key keyboard with five keys: a, ctrl-c, ctrl-x, ctrl-v and ctrl-a. Key a outputs a letter A on the screen; Ctrl-c copies the currently selected letters to the clipboard; Ctrl-x copies the currently selected letters to the clipboard and empties the selected letters; Ctrl-v outputs letters from the current clipboard to the screen; Ctrl-a selects all the letters on the current screen. Be careful:
1 The clipboard is initially empty and new content will be copied to the clipboard to overwrite the original content
2 ctrl-a is not valid when there are no letters on the screen
3 ctrl-c and ctrl-x are not valid when no letters are selected
4 When a letter is selected, the two output keys a and ctrl-v empty the selected letter before outputting it
Given a series of keyboard inputs, output the number of letters on the final screen.
Enter a description:
Input is one line, to simplify parsing, use the numbers 1 2 3 4 5 to represent the input of a, ctrl-c, ctrl-x, ctrl-v, ctrl-a five keys, the numbers are separated by spaces
Output description:
Output a number for the number of letters on the final screen
Example 1:
input
1 1 1
output
3
Explain
Type 3 A in a row, so the letters on the screen are 3
Example 2:
input
1 1 5 1 5 2 4 4
output
2
Explain
Ctrl-a selects the two a after entering two a, then two a selected when entering a are cleared first, so there is only one a on the screen at this time, followed by ctrl-a, ctrl-c selects and copies this a. The last two ctrl-v output two a on the screen, so the length of the letter on the screen is 2 (the first ctrl-v empties the A on the screen).
Answer:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { String totalStr=in.nextLine(); int count = 0; int copyCount = 0; int selCount = 0; boolean overOp = false; for (char op : totalStr.toCharArray()) { if (op == '1') { //a count = selCount > 0 ? 1 : count + 1; selCount = 0; } else if (op == '2') { //copy copyCount = selCount; } else if (op == '3') { //shear count -= selCount; copyCount = selCount; selCount = 0; } else if (op == '4') { //paste count -= selCount; selCount = 0; count += copyCount; } else if (op == '5') { //Select All selCount = count; } } System.out.println(count); } } }
2. N-ary Subtraction
Implements a string-based N-mechanism subtraction.
The two input strings need to be subtracted according to the given N-ary, and the positive and negative symbols and strings representing the results are output.
Enter a description:
Input: Three parameters.
The first parameter is a binary N-value in integer form, and the range of N-values is greater than or equal to 2 and less than or equal to 35.
The second parameter is the subtracted string;
The third parameter is the minus string. Valid characters include 09 and the lowercase letter az. The maximum number of valid characters in a string is 100, plus 0 at the end.
Restrictions:
The subtracted and subtracted inputs cannot start with a string of 0 except for a separate zero.
If there are exceptions to the input or to the calculation, then output-1 should indicate an error.
Output description:
Output: 2.
One is the result of subtraction, -1 is an error, 0 is an integer, and 1 is a negative number.
The second is a string representing the result.
Example 1:
input
2 11 1
output
0 10
Explain
Calculate 11-1 binary, normal, 0 sign is positive, result is 10
Example 2:
input
8 07 1
output
-1
Explain
In octal, check that the minus does not meet the requirements of non-zero leading, return result is -1, no other result content.
Answer:
import java.util.ArrayList; import java.util.Scanner; import java.util.TreeSet; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String input = sc.nextLine(); Integer request = Integer.parseInt(sc.nextLine()); sc.close(); TreeSet<Integer> set = new TreeSet<>(); for (String str : input.split(",")) { if (str.contains("-")) { String[] split = str.split("-"); int start = Integer.parseInt(split[0]); int end = Integer.parseInt(split[1]); for (int i = start; i <= end; i++) { set.add(i); } } else { set.add(Integer.parseInt(str)); } } set.remove(request); ArrayList<Integer> list = new ArrayList<>(set); StringBuilder sb = new StringBuilder(); Integer start = list.get(0); Integer last = start; for (int i = 1; i < list.size(); i++) { Integer cur = list.get(i); if (cur == last + 1) { last = cur; } else { append(sb, start, last); start = last = cur; } } append(sb, start, last); System.out.println(sb.substring(0, sb.length() - 1)); } private static void append(StringBuilder sb, Integer start, Integer last) { if (start.equals(last)) { sb.append(last).append(","); } else { sb.append(start).append("-").append(last).append(","); } } }
3. TLV decoding
TLV encoding is encoded in [Tag Length Value] format. Cells in a stream are identified by Tag. Tag is unique and does not repeat in the stream. Length is the length of the cell Value, and Value is the value of the cell.
The stream begins with a Tag of a cell, Tag is fixed for one byte, Length is fixed for two bytes, and the byte order is small endpoint.
Given the stream encoded in TLV format and the cell Tag that needs to be decoded, output the Value of that cell.
Lower case letters are not included in the 16-mechanism characters of the input stream, and lower case letters are not required in the 16-bit string of the output. The maximum length of a stream string is not more than 50,000 bytes.
Enter a description:
The first line of input is a string representing the Tag of the cell to be decoded.
The second line of input is a string representing the 16-bit stream to be decoded, with bytes separated by spaces.
Output description:
Outputs a string representing the Value of the cell to be decoded in hexadecimal.
Example 1:
input
31
32 01 00 AE 90 02 00 01 02 30 03 00 AB 32 31 31 02 00 32 33 33 01 00 CC
output
32 33
Explain
The Tag of the cell to be resolved is 31, matching starts at the beginning of the stream, and Tag is 32 with a cell length of 1 (01 00, small end order is 1). The Tag of the second cell is 90, and its length is 2; The third cell has a Tag of 30 and a length of 3; The fourth cell has a Tag of 31, which is 2 (02,00), so return the two bytes after the length, 32,33.
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextLine()) {// Note that if the input is multiple test cases, use the while loop to process multiple test cases String key=in.nextLine(); String[] arr=in.nextLine().replaceAll("[a-z]", "").split("[ ]"); String tag=""; int length; String value=""; for(int i=0;i<arr.length;) { tag=""; length=0; value=""; tag=arr[i]; length=Integer.valueOf(arr[i+2]+arr[i+1], 16); for(int j=1;j<=length;j++) { value+=arr[i+2+j]+" "; } if(key.equals(tag)) { System.out.println(value.trim()); } // System.out.println(tag+" "+length+" "+value.trim()); i=i+2+length+1; } } } }
4. VLAN Resource Pool
VLAN is a technology for logical partitioning of LAN devices. To identify different VLANs, the concept of VLAN ID (an integer between 1 and 4094) is introduced. Defines a resource pool for a VLAN ID (hereinafter referred to as the VLAN resource pool), where successive VLANs are represented by start VLAN-end VLANs, discontinuous single integers, and all VLANs are connected by English commas. There is now a VLAN resource pool. Business needs to request a VLAN from the resource pool, and you need to output the resource pool after removing the requested VLAN from the VLAN resource pool.
Enter a description:
The first behavior is the VLAN resource pool in string format, the second behavior is the VLAN to which the business is requesting, and the value range of the VLAN is an integer between [1,4094].
Output description:
Remove the VLAN resource pool in string format after the requested VLAN from the input VLAN resource pool. The output requirements satisfy the format in the title description and are output in ascending order from small to large VLANs.
If the requested VLAN is not in the original VLAN resource pool, output the ascending ordered string of the original VLAN resource pool.
Example 1:
input
1-5
2
output
1,3-5
Explain
There are VLAN 1, 2, 3, 4, 5 in the original VLAN resource pool. After removing 2 from the resource pool, there are VLAN 1, 3, 4, 5 left. The result is 1,3-5 in the title description format and ascending order.
Example 2:
input
20-21,15,18,30,5-10
15
output
5-10,18,20-21,30
Explain
There are VLANs 5, 6, 7, 8, 9, 10, 15, 18, 20, 21, 30 in the original VLAN resource pool. After removing 15 from the resource pool, the remaining VLANs in the resource pool are 5, 6, 7, 8, 9, 10, 18, 20, 21, 30. The result is 5-10, 18, 20-21, 30 in ascending order according to the Title Description format.
Example 3:
input
5,1-3
10
output
1-3,5
Explain
The original VLAN resource pool contains VLAN 1, 2, 3, 5. The requested VLAN 10 is not in the original resource pool. The output of the original resource pool is 1-3,5 after formatting the title description and sorting it in ascending order.
Remarks:
The number of VLANs in the input VLAN resource pool is an integer between [2-4094], the VLANs in the resource pool are not duplicated and legal ([1,4094]), and the input is out of order.
Answer:
Solution 1:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = null; int[] vlan = new int[4094]; try { str = br.readLine(); int num = Integer.parseInt(br.readLine()); String[] split = str.split(","); for (String s : split) { try { int index = Integer.parseInt(s); if (index == num) continue; vlan[index] = 1; } catch (NumberFormatException exception) { if (s.contains("-")) { String[] s_s = s.split("-"); int first = Integer.parseInt(s_s[0]); int end = Integer.parseInt(s_s[1]); for (int i = first; i <= end; i++) { if (num != i) { vlan[i] = 1; } } } } } StringBuilder result = new StringBuilder(); for (int i = 1; i < vlan.length; i++) { if (vlan[i] == 1) { result.append(","); result.append(i); if (++i < vlan.length && vlan[i] == 1) { result.append("-"); while (vlan[++i] == 1) { } result.append(i - 1); } } } String resultStr = result.toString(); if (result.indexOf(",") == 0) { resultStr = resultStr.substring(1); } System.out.println(resultStr); } catch (IOException e) { e.printStackTrace(); } } }
Solution 2:
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.nextLine(); String[] array = s.split(","); Set<Integer> set = new HashSet(); for (int i = 0; i < array.length; i++) { if (array[i].length() == 0) { continue; } String[] tempArray = array[i].split("-"); if (tempArray.length == 2) { for (int j = Integer.valueOf(tempArray[0]); j <= Integer.valueOf(tempArray[1]); j++) { set.add(j); } }else{ set.add(Integer.valueOf(tempArray[0])); } } String filter = in.nextLine(); set.remove(Integer.valueOf(filter)); List<Integer> list = new ArrayList(set); if (list.size() == 1) { System.out.println(list.get(0)); return; } Collections.sort(list); StringBuilder result = new StringBuilder(); for (int i = 0; i < list.size()-1; i++) { if (list.get(i) == list.get(i + 1) - 1) { result.append(","+list.get(i)); while (i<list.size()-1&&list.get(i) == list.get(i + 1) - 1) { i++; } result.append("-" + list.get(i)); }else{ result.append("," + list.get(i)); } if (i == list.size() - 2) { result.append("," + list.get(i + 1)); } } String resultString = result.toString(); if (resultString.length()>0&&resultString.charAt(0) == ',') { resultString=resultString.substring(1); } System.out.println(resultString); } }
5. Queue by height and weight
A school holds a sports meeting. Students are identified by number (1, 2, 3...n). Now they need to rank from low to high. For people of the same height, they should rank from light to heavy. For people of the same height and weight, the original numbering sequence was maintained. Please output the number of students arranged.
Enter a description:
Two sequences, each consisting of n positive integers (0 < n <= 100). The values in the first sequence represent height, and the values in the second sequence represent weight.
Output description:
Arrange the results, each value being the student number in the original sequence, starting from 1
Example 1:
input
4
100 100 120 130
40 30 60 50
output
2 1 3 4
Explain
The first number 2 of the output indicates that the person's original number is 2, that is, the person who is 100 and weighs 30. Since he is the same height as the number 1 person but weighs less, he ranks first.
Example 2:
input
3
90 110 90
45 60 45
output
1 3 2
Explain
Both 1 and 3 have the same height and weight, so you need to rank 1 first in position, not 3 1 2
Answer:
Solution 1:
import java.util.Arrays; import java.util.Scanner; public class Main { static class Node implements Comparable<Node>{ int i; int h; int w; Node(int i,int h,int w){ this.i = i ; this.h = h ; this.w = w ; } @Override public int compareTo(Node o){ if(h != o.h) return h - o.h ; if(w!= o.w) return w - o.w ; return i - o.i; } } public static void main(String[] args){ Scanner in = new Scanner(System.in) ; while(in.hasNext()){ int n = in.nextInt() ; int [] h = new int [n] ; int [] w = new int [n] ; for(int i = 0;i < n;i++){ h[i] = in.nextInt() ; } for(int i = 0;i < n; i++){ w[i]= in.nextInt(); } Node[] nodes = new Node [n]; for(int i = 0;i < n; i++){ nodes[i] = new Node(i+1,h[i],w[i]); } Arrays.sort(nodes); for(int i =0;i<n;i++){ System.out.printf("%d%c",nodes[i].i,1 == n-1 ? '\n':' '); } } } }
6. Flip article fragments by index range
Enter an English article fragment, flip the word order of the specified interval, and use punctuation as normal letters. For example, if you enter the string "I am a developer." and the interval [0,3], you output "developer. a am I".
String reverseWords(String s, int start, int end)
Enter a description:
Three parameters are separated by a line break. The first parameter is the English article content, which is the English string, the second parameter is the flip start word subscript (subscript starts from 0), and the third parameter is the end word subscript.
Output description:
Flipped English article fragment Output all words separated by a half-space
Example 1:
input
I am a developer.
1
2
output
I a am developer.
Example 2:
input
hello world!
0
1
output
world! hello
Explain
Input strings can contain extra spaces before or after them, but reversed characters cannot.
Example 3:
input
I am a developer.
0
3
output
developer. a am I
Explain
If there is extra space between two words, reduce the space between the inverted words to only one.
Example 4:
input
Hello!
0
3
output
EMPTY
Explain
"EMPTY" is output uniformly if there is only one word or no valid word in the specified flip interval
Answer:
Solution 1:
import java.util.ArrayList; import java.util.Scanner; import java.util.TreeSet; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String input = sc.nextLine(); Integer request = Integer.parseInt(sc.nextLine()); sc.close(); TreeSet<Integer> set = new TreeSet<>(); for (String str : input.split(",")) { if (str.contains("-")) { String[] split = str.split("-"); int start = Integer.parseInt(split[0]); int end = Integer.parseInt(split[1]); for (int i = start; i <= end; i++) { set.add(i); } } else { set.add(Integer.parseInt(str)); } } set.remove(request); ArrayList<Integer> list = new ArrayList<>(set); StringBuilder sb = new StringBuilder(); Integer start = list.get(0); Integer last = start; for (int i = 1; i < list.size(); i++) { Integer cur = list.get(i); if (cur == last + 1) { last = cur; } else { append(sb, start, last); start = last = cur; } } append(sb, start, last); System.out.println(sb.substring(0, sb.length() - 1)); } private static void append(StringBuilder sb, Integer start, Integer last) { if (start.equals(last)) { sb.append(last).append(","); } else { sb.append(start).append("-").append(last).append(","); } } }
7. Counting Game
100 people in a circle, each with a code, numbering from 1 to 100. They report the number one by one, and the person reporting as M automatically exits the circle, then the next person reports from one until the remaining number is less than M. What was the original number of the last remaining person?
Enter a description:
Enter an integer parameter M
Output description:
If the input parameter M is less than or equal to 1 or greater than or equal to 100, the output "ERROR!"; Otherwise, the output numbering string will be separated by English commas in the order of the original numbering from smallest to largest
Example 1:
input
3
output
58,91
Explain
Enter M to 3, with the last two remaining
Example 2:
input
4
output
34,45,97
Explain
Enter M for 4, with the last three remaining
Answer:
Solution 1:
import java.util.Scanner; import java.util.Collections; import java.util.ArrayList; public class Main { static class node{ int val; node next = null; node(int val){this.val=val;} } public static void main(String[] args) { Scanner in = new Scanner(System.in); int M = in.nextInt(); if(M<=1||M>=100) System.out.println("ERROR!"); else{ ArrayList<Integer> ans = new ArrayList<>(); node head = new node(1),pre = head; for(int i=2;i<=100;i++){ node now = new node(i); pre.next=now; pre = now; } pre.next=head; //num records the number of people left, k records the current number of reports int num = 100,k=1; while(true){ k++; pre = pre.next; head = head.next; //If the number of reports is M, delete the nodes of the chain table if(k==M){ pre.next=head.next; head=pre.next; k=1; num--; } if(num<M){ pre=head; do{ ans.add(head.val); head=head.next; }while(head !=pre); break; } } Collections.sort(ans); for(int i=0;i<ans.size();i++){ System.out.printf("%d%c",ans.get(i),i==ans.size()-1?'\n':','); } } } }
Solution 2:
import java.util.*; public class Main { public static void main(String[] args) { List<Integer> peopleNos = new ArrayList(100); for(int i = 1; i <= 100;i++) { peopleNos.add(i); } Scanner scan = new Scanner(System.in); int m = scan.nextInt(); if (m <= 1 || m >= 100) { System.out.println("ERROR!"); return; } int num = 0; int index = 0; while (peopleNos.size() >= m) { num++; if (index >= peopleNos.size()) { index = 0; } Integer no = peopleNos.get(index); if (num == m) { //Delete this element, and the next element counts from 1 peopleNos.remove(no); num = 0; index--; } index++; } StringBuilder builder = new StringBuilder(); int count = 0; for (Integer i : peopleNos) { builder.append(i); if (count != peopleNos.size() - 1) { builder.append(","); } count++; } System.out.println(builder.toString()); } }
8. Competition
There are N competitors in the competition, numbered from 1 to N (3<=N<=100), and M (3<=M<=10) judges scoring the competitors. The scoring rules give each judge a maximum of 10 points and a minimum of 1 point.
Please calculate the number of the top 3 scorers. If the scores are the same, the player with the highest score ranks first (10 points are the same, the number of 9 points is compared, and so on, no more than one player will have the same score in the use case).
Enter a description:
The first behavior is two positive integers separated by a half-corner comma. The first number represents M (3<=M<=10) judges, and the second number represents N (3<=N<=100) players.
Lines 2 to M+1 are half-comma-separated integer sequences that indicate the judges'scores for each player, the number 0 subscript indicates the number 1 player's score, the number 1 indicates the number 2 player's score, and so on.
Output description:
Number of the top 3 runners.
Note: If the input is an exception, the output-1, such as M, N, and score are not within the range.
Example 1:
input
4,5
10,6,9,7,6
9,10,6,7,5
8,10,6,5,10
9,10,8,4,9
output
2,1,5
Explain
The first row contains four judges and five contestants
The matrix represents 4*5, each number is the player's number, and each line represents the order of the judges'ratings.
No. 2 runner has 36 points in 1st place, No. 1 runner 36 points in 2nd place, No. 5 runner 30 points (No. 2 has 3 points in 10th place, No. 1 has only 1 point in 10th place, so No. 2 runs first).
Example 2:
input
2,5
7,3,5,4,2
8,5,4,4,3
output
-1
Explain
There are only 2 Judges and a minimum of 3 are required
Example 3:
input
4,2
8,5
5,6
10,4
8,9
output
-1
Explain
Only 2 participants, minimum 3 required
Example 4:
input
4,5
11,6,9,7,8
9,10,6,7,8
8,10,6,9,7
9,10,8,6,7
output
-1
Explain
The first judge gives the first player an 11, invalid score
Answer:
Solution 1 (python):
import sys input = """ 4,5 10,6,9,7,6 9,10,6,7,5 8,10,6,5,10 9,10,8,4,9""" if __name__ == "__main__": def slution(): # Read n of first line try: p, x = sys.stdin.readline().strip().split(",") p = int(p) x = int(x) except: print(-1) return else: if (p >= 3 and p <= 10) and (x >= 3 and x <= 100): dp = [[0 for i in range(p)] for i in range(x)] for i in range(p): try: # Data for each row line = sys.stdin.readline().strip().split(",") except: print(-1) return else: for index, num in enumerate(line): try: num = int(num) if num >= 1 and num <= 10: dp[index][i] = num else: print(-1) return except: print(-1) return res = [] for index, i in enumerate(dp): i.sort() i.reverse() res.append((sum(i), i, index+1)) res.sort(key=lambda x: (x[0], x[1])) res.reverse() print(f"{res[0][2]},{res[1][2]},{res[2][2]}") else: print(-1) slution()
9. Optimal time period for finding interface success rate
Interface success rate exchanged between services is a key quality feature of service invocation. Interface failure rate over a period of time is expressed as an array. Each element in the array is a failure rate value per unit time. The number in the array is an integer of 0-100. Given a value (minAverageLost), it represents the average failure rate tolerance value over a period of time. That is, the average failure rate is less than or equal to minAverageLost, finding the longest time period in the array, and returning NULL directly if not found.
Enter a description:
The input has two lines, the first behavior {minAverageLost}, the second behavior {array}, the array elements are separated by spaces ("). MinAverageLost and the elements in the array have values ranging from 0 to 100, and the number of elements in the array cannot exceed 100.
Output description:
Find the longest period with an average value less than or equal to minAverageLost, output array subscript pairs, format {beginIndex}-{endIndx} (subscript starts at 0), if there are multiple longest periods at the same time, output multiple subscript pairs with spaces (") stitching between them, and sort them from smallest to largest subscript pairs.
Example 1:
input
1
0 1 2 3 4
output
0-2
Explain
A, input explanation: minAverageLost=1, array [0, 1, 2, 3, 4]
B, the average of the first three elements is 1, so the array's first to third array subscripts are 0-2
Example 2:
input
2
0 0 100 2 2 99 0 2
output
0-1 3-4 6-7
Explain
A, input explanation: minAverageLost=2, array [0, 0, 100, 2, 2, 99, 0, 2]
B. By calculating the maximum time period that is less than or equal to 2, the array subscript is 0-1 or [0, 0], the array subscript is 3-4 or [2, 2], and the array subscript is 6-7 or [0, 2]. All three parts satisfy the requirement that the average value is less than 2, so the output is 0-1 3-4 6-7
Answer:
Solution 1:
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { private static List<String> sResultList = new ArrayList<>(); private static int sCurrentLength = 0; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { int minAvg = Integer.parseInt(scanner.nextLine().trim()); String[] strings = scanner.nextLine().trim().split(" "); List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < strings.length; i++) { list.add(Integer.parseInt(strings[i])); } getPeriod(minAvg, list); if (!sResultList.isEmpty()) { for (int i = 0; i < sResultList.size(); i++) { System.out.print(sResultList.get(i)); System.out.print(" "); } } } } private static void getPeriod(int minAvg, List<Integer> list) { sResultList.clear(); sCurrentLength = 0; for (int start = 0; start < list.size() - 1; start++) { for (int end = start + 1; end < list.size(); end++) { int sum = getSum(list, start, end); String result = ""; int length = end - start + 1; if (sum == 0 && minAvg >= 0) { result = start + "-" + end; } else { if (sum <= minAvg * length) { result = start + "-" + end; } } if (result.contains("-")) { if (length == sCurrentLength) { sResultList.add(result); } if (length > sCurrentLength) { sResultList.clear(); sResultList.add(result); sCurrentLength = length; } } } } } private static int getSum(List<Integer> list, int start, int end) { int sum = 0; for (int i = start; i <= end; i++) { sum += list.get(i); } return sum; } }
10. Find the majority and median
1. Majority refers to the number of times that occur in a set of data. Majority can be multiple
2. Median is the number that arranges a set of data from small to large, the middle number. If the number of data in this set is odd, the middle number is the median. If the number of data in this set is even, dividing the sum of the two middle numbers by two will result in the median.
3. Find the majority of elements in an integer array and form a new array to find the median of the new array
Enter a description:
Enter a one-dimensional integer array with a size range of 0<N<1000 and a value range of 0<E<1000 for each element in the array.
Output description:
Median of a new array of output majority
Example 1:
input
10 11 21 19 21 17 21 16 21 18 15
output
21
Example 2:
input
2 1 5 4 3 3 9 2 7 4 6 2 15 4 2 4
output
3
Example 3:
input
5 1 5 3 5 2 5 5 7 6 7 3 7 11 7 55 7 9 98 9 17 9 15 9 9 1 39
output
7
Answer:
Solution 1:
import java.util.*; public class Main { public static void main(String[] args) { // input Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); String[] s = input.split(" "); int[] nums = new int[s.length]; for (int i = 0; i < nums.length; i++) { nums[i] = Integer.parseInt(s[i]); } scanner.close(); // Get the array of numbers and the median Integer[] manyNums = getManyArr(nums); int medium = 0; int len = manyNums.length; if (len % 2 == 0) { medium = (manyNums[len / 2 - 1] + manyNums[len / 2]) / 2; } else { medium = manyNums[len / 2]; } System.out.println(medium); } private static Integer[] getManyArr(int[] arr) { if (arr == null) { return new Integer[0]; } // Convert array elements and occurrences to key-value Map<Integer, Integer> countMap = new HashMap<>(); for (int i = 0; i < arr.length; i++) { int current = arr[i]; if (countMap.containsKey(current)) { Integer count = countMap.get(current); countMap.put(current, ++count); } else { countMap.put(current, 1); } } // Get the most occurrences int countMax = 0; for (int value : countMap.values()) { if (value > countMax) { countMax = value; } } // Get the majority and sort List<Integer> list = new ArrayList<>(); for (int key : countMap.keySet()) { if (countMap.get(key) == countMax) { list.add(key); } } list.sort(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1 - o2; } }); Integer[] newArr = new Integer[list.size()]; return list.toArray(newArr); } }
Solution 2:
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); HashMap<Integer, Integer> map = new HashMap<>(); int max = 0; List<Integer> list =new ArrayList<>(); while (in.hasNextInt()) { int num = in.nextInt(); map.merge(num,1,(a,b)->a+b); if (map.get(num)>max){ list.clear(); list.add(num); max = map.get(num); }else if (map.get(num)==max){ list.add(num); } } list.sort(Integer::compare); int n = list.size(); if (n%2==0){ System.out.print((list.get(n/2)+list.get(n/2-1))/2); }else{ System.out.print(list.get(n/2)); } } }
11. Disk Capacity Sorting
Disk capacity units are commonly used in M, G, T levels. The conversion relationship between them is 1T = 1024G, 1G = 1024M. Now given the capacity of n disks, please sort them steadily from small to large. For example, given the capacity of 5 disks, 1T, 20M, 3G, 10G6T, 3M12G9M, the result is 20M, 3G, 3M12G9M, 1T, 10G6T. Note that the units can be repeated, and the capacity represented by 3M 12G 9M above is 3M+12G+9M, equal to 12M 12G.
Enter a description:
The first line of input contains an integer n (2 <= n <= 100), representing the number of disks, and the next n lines, each with a string of length greater than 2 and less than 30, representing the capacity of the disk, consisting of one or more substrings formatted as m v, where M represents the capacity size and V represents the capacity unit, such as 20M, 1T, 30G, 10G6T, 3M12G9M.
The disk capacity m ranges from 1 to 1024 positive integers, and the capacity unit v only includes the M, G, T mentioned in the title. The conversion relationships are described in the title.
Output description:
Output n rows representing the sorted result of N disk volumes.
Example 1:
input
3
1G
2G
1024M
output
1G
1024M
2G
Explain
1G and 1024M have equal capacity, stable sorting requires that their original relative positions be preserved, so 1G is before 1024M
Example 2:
input
3
2G4M
3M2G
1T
output
3M2G
2G4M
1T
Explain
1T has a capacity greater than 2G4M, 2G4M has a capacity greater than 3M2G
Answer:
Solution 1:
#include <iostream> #include <algorithm> #include <vector> using namespace std; int getSize(string s) { int ans = 0; int curNum = 0; for (char c: s) { if (isdigit(c)) { curNum = curNum * 10 + (c - '0'); } else { if (c == 'M') { ans += curNum; } else if (c == 'G') { ans += curNum * 1024; } else if (c == 'T') { ans += curNum * 1024 * 1024; } curNum = 0; } } return ans; } bool cmp(const string& s1, const string& s2) { return getSize(s1) < getSize(s2); } int main() { string s; int n; cin >> n; vector<string> size; while(n--) { cin >> s; size.push_back(s); } stable_sort(size.begin(), size.end(), cmp); for (string s: size) { cout << s << endl; } return 0; }
12. Word Solitaire
The rule of word Solitaire is that the first letter of a word used in Solitaire must have the same ending letter of the previous word. When there are multiple words with the same initial letter, take the word with the longest length and the word with the lowest dictionary order if the lengths are equal. Words that have already participated in Solitaire cannot be reused.
Now given an array of words that are composed entirely of lowercase letters, and specify one of the words as the starting word for word joining, output the longest word string, which is a concatenation of words with no spaces in between.
Enter a description:
The first line of input is a non-negative integer indicating the index K of the starting word in the array, 0 <= K < N;
The second line of input is a non-negative integer representing the number N of words.
The next N lines represent the words in the word array.
Output description:
Output a string representing the final stitched word string.
Example 1:
input
0
6
word
dd
da
dc
dword
d
output
worddwordda
Explain
First determine the starting word, followed by the word D word, which starts with D and has the longest length, and then the word D d, da, dc, which starts with D and has the longest length, takes the Da with the smallest dictionary order, and outputs word D word DA at the end.
Example 2:
input
4
6
word
dd
da
dc
dword
d
output
dwordda
Explain
First determine the starting word dword, then the longest D d, da, dc that starts with d, take the lowest DA in dictionary order, and output DWORD DA at last.
Remarks:
The number of words N ranges from [1, 20];
The length of a single word ranges from [1, 30];
Answer:
Solution 1 (python3):
while True: try: index = int(input()) n = int(input()) data = [] for _ in range(n): data.append(input()) res = data[index] data.remove(data[index]) for i in range(n - 1): target = res[-1] aa1 = [] aa2=[] for j in data: if j.startswith(target): aa1.append(j) aa2.append(len(j)) if aa1: max_len = max(aa2) if aa2.count(max_len)==1: res+=aa1[aa2.index(max_len)] data.remove(aa1[aa2.index(max_len)]) else: aa3=list(filter(lambda x:len(x)==max_len,aa1)) aa3.sort() res+=aa3[0] data.remove(aa3[0]) else: break print(res) except: break
12. k Arrangement
Given the parameter n, there will be n integers from 1 to n: 1, 2, 3,..., n, the N numbers have n! Arrangement of species.
All permutations are listed in ascending order of size and marked one by one. When n = 3, all permutations are as follows:
"123"
"132"
"213"
"231"
"312"
"321"
Given n n n n n n n and k, return the kth permutation.
Enter a description:
Enter two lines, the first behavior n, the second behavior k, the range of a given n is [1,9], and the range of a given K is [1,n!].
Output description:
Output number in position k.
Example 1:
input
3
3
output
213
Explain
3 has 123,132,213... and position 3 has 213
Example 2:
input
2
2
output
21
Explain
2 has 1221, so the second position is 21
Answer:
Solution 1:
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); List<Integer> list = new ArrayList<>(); int[] arr = new int[n + 1]; arr[0] = 1; for (int i = 1; i <= n; i++) { list.add(i); arr[i] = arr[i - 1] * i; } k--; StringBuffer stringBuffer = new StringBuffer(); for (int i = n - 1; i >= 0; i--) { int index = k / arr[i]; stringBuffer.append(list.remove(index)); k -= index * arr[i]; } System.out.println(stringBuffer.toString()); } }
13. Shunzi, the landowner
In a landlord poker game, the order of playing cards from small to large is: 3,4,5,6,7,8,9,10,J,Q,K,A,2. Players can play cards in the following formats: sheet, pair, circus, airplane, bomb, etc.
The playing rules of Shunzi are as follows: at least five playing cards consisting of continuously increasing cards from small to Dalian, and they cannot contain two.
For example: {3,4,5,6,7}, {3,4,5,6,7,8,9,10,J,Q,K,A} are all valid cistrons; However, {J,Q,K,A,2}, {2,3,4,5,6}, {3,4,5,6}, {3,4,5,6} and so on are not cistrons.
Given an array of 13 cards, if a sequence meets the rules for playing cards, output the sequence.
If there is more than one circus, output one circus per line, and the first card of the circus must be sized from small to large.
If no sequence meets the rules for playing cards, output No.
Enter a description:
13 cards in any order, each number of cards is separated by a space. The number of each card is legal and does not include King or King:
2 9 J 2 3 4 K A 7 9 A 5 6
No need to consider input as an exception character
Output description:
The number of each playing card is separated by a space:
3 4 5 6 7
Example 1:
input
2 9 J 2 3 4 K A 7 9 A 5 6
output
3 4 5 6 7
Explain
Of the 13 cards, there is only one group of cistrons that can be composed: 34,5,6 7
Example 2:
input
2 9 J 10 3 4 K A 7 Q A 5 6
output
3 4 5 6 7
9 10 J Q K A
Explain
Of the 13 cards, two groups of cistrons can be formed, from small to large: 345 6 7 and 9 10 J Q K A
Example 3:
input
2 9 9 9 3 4 K A 10 Q A 5 6
output
No
Explain
Of the 13 cards, you can't make a shunzi
Answer:
Solution 1:
import java.util.*; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String inputPoker = scanner.nextLine(); String[] allPoker = inputPoker.split(" "); Queue<Integer> sortedInput = Arrays .stream(allPoker) .filter(poker -> !poker.equals("2")) .map(poker -> { switch (poker) { case "J": return 11; case "Q": return 12; case "K": return 13; case "A": return 14; default: return Integer.parseInt(poker); } }) .sorted().collect(Collectors.toCollection(LinkedList::new)); List<SortedBean> allSortedList = new ArrayList<>(); int resultCount = 0; int lastValue = 0; while (!sortedInput.isEmpty()) { Integer currentValue = sortedInput.remove(); if (lastValue == 0) { SortedBean sortedBean = new SortedBean(); sortedBean.currLastValue = currentValue; ArrayList<Integer> allData = new ArrayList<>(); allData.add(currentValue); sortedBean.allData = allData; allSortedList.add(sortedBean); } else { if (currentValue - lastValue == 0) { boolean isAdded = false; for (SortedBean sortedBean : allSortedList) { if (currentValue - sortedBean.currLastValue == 1) { sortedBean.currLastValue = currentValue; sortedBean.allData.add(currentValue); isAdded = true; break; } } if (!isAdded) { SortedBean sortedBean = new SortedBean(); sortedBean.currLastValue = currentValue; ArrayList<Integer> allData = new ArrayList<>(); allData.add(currentValue); sortedBean.allData = allData; allSortedList.add(sortedBean); } } else if (currentValue - lastValue == 1) { for (SortedBean sortedBean : allSortedList) { if (sortedBean.currLastValue == lastValue) { sortedBean.currLastValue = currentValue; sortedBean.allData.add(currentValue); break; } } } else { SortedBean sortedBean = new SortedBean(); sortedBean.currLastValue = currentValue; ArrayList<Integer> allData = new ArrayList<>(); allData.add(currentValue); sortedBean.allData = allData; allSortedList.add(sortedBean); } } lastValue = currentValue; } allSortedList.sort(Comparator.comparingInt(o -> o.allData.size())); for (SortedBean sortedBean : allSortedList) { if (sortedBean.allData.size() >= 5) { StringBuilder stringBuilder = new StringBuilder(); for (Integer integer : sortedBean.allData) { stringBuilder.append(getValue(integer)).append(" "); } System.out.println(stringBuilder.substring(0, stringBuilder.length() - 1)); resultCount++; } } if (resultCount == 0) { System.out.println("No"); } } } private static String getValue(int src) { switch (src) { case 11: return "J"; case 12: return "Q"; case 13: return "K"; case 14: return "A"; default: return src + ""; } } private static class SortedBean { public int currLastValue; private List<Integer> allData; @Override public String toString() { return "SortedBean{" + "currLastValue=" + currLastValue + ", allData=" + allData + '}'; } } }
14. Non-strictly Incremental Continuous Number Sequence
Enter a string containing only uppercase and lowercase letters and numbers to find the length of the longest non-strictly increasing continuous number sequence contained in the string (for example, 12234 is a non-strictly increasing continuous number sequence).
Enter a description:
Enter a string containing only uppercase and lowercase letters and numbers, and enter a string of up to 255 characters.
Output description:
The length of the longest non-strictly increasing sequence of continuous numbers
Example 1:
input
abc2234019A334bc
output
4
Explain
2234 is the longest non-strictly increasing sequence of continuous numbers, so the length is 4.
Answer:
Solution 1:
//This is an example of a single-line, multi-line I/O specification for an exam. It does not require submission and is not scored.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) {// Note that if the input is multiple test cases, use the while loop to process multiple test cases String str = in.nextLine(); if (str.length()==1&&str.charAt(0)>='0'&&str.charAt(0)<='9'){ System.out.println(1); continue; } boolean flag = false; char[] c = str.toCharArray(); int size = str.length(); int max = 1; int length = 1; for (int i = 1; i < size ; i++) { if ((c[i - 1] >= '0' && c[i - 1] <= '9') || (c[i] >= '0' && c[i] <= '9')) { flag = true; } if (c[i-1] <= c[i]&&c[i-1]>='0'&&c[i]<='9') { length++; if (length > max) { max = length; } continue; } else { length = 1; } } if (flag == true) { System.out.println(max); } else { System.out.println(0); } } } }
14. Shift
Kids from two kindergarten classes mix up in the queue. Each kid knows if he or she is in the same class as the previous one. Please help find out the children from the same class.
The number of the child is an integer, Y is used for classes with the previous child and N is used for classes with different children.
Enter a description:
Enter a space-separated number for your child and a symbol for whether or not you are in the same class.
For example: 6/N 2/Y 3/N 4/Y means there are 4 children in total, 2 and 6 in the same class, 3 and 2 in different classes, 4 and 3 in the same class.
Among them, the total number of children is not more than 999, each child number is greater than 0, less than or equal to 999.
Input format error is not considered.
Output description:
The output is two lines, each of which records the number of a class child, separated by spaces. And:
1. Numbers need to be sorted in ascending order of size, with the first small number in the shift record being in the first line.
2. If there is only one class of children, the second behavior is empty.
3. If the input does not meet the requirements, the direct output string ERROR.
Example 1:
input
1/N 2/Y 3/N 4/Y
output
1 2
3 4
Explain
2 is marked Y, so 1 is in the same class.
Class 3 is marked as N, so classes 1 and 2 are different.
Class 4 is marked Y, so class 3.
So 1, 2, 3, 4, the output is
1 2
3 4
Answer:
Solution 1:
import java.util.*; import java.util.ArrayList; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { try{ Scanner scan = new Scanner(System.in); String in = scan.nextLine(); String[] a = in.split(" "); ArrayList<Integer> l1 = new ArrayList<Integer>(999); ArrayList<Integer> l2 = new ArrayList<Integer>(999); ArrayList<Integer> l0 = null; boolean same = true; for (int i = a.length - 1; i >= 0; i--) { Integer num = Integer.parseInt(a[i].substring(0,a[i].indexOf("/"))); if(num<=0||num>999){ throw new Exception(); } same = a[i].endsWith("Y"); if (i == a.length - 1) { l0 = l1; } l0.add(num); if(!same){ l0 = l0==l1?l2:l1; } } Collections.sort(l1); Collections.sort(l2); if(new HashSet(l1).size()<l1.size()||new HashSet(l2).size()<l2.size()){ throw new Exception(); } if(l2.size()!=0 && l1.get(0)>l2.get(0)){ System.out.println(l2.stream().map(String::valueOf).collect(Collectors.joining(" "))); System.out.println(l1.stream().map(String::valueOf).collect(Collectors.joining(" "))); }else{ System.out.println(l1.stream().map(String::valueOf).collect(Collectors.joining(" "))); System.out.println(l2.stream().map(String::valueOf).collect(Collectors.joining(" "))); } }catch(Exception e){ System.out.println("ERROR"); } } }
15. Candy Dividing
Xiao Ming grabs a handful of candy at will from the candy box, and each time Xiao Ming takes out half of the candy and distributes it to the students.
When the candy is not evenly distributed, Xiao Ming can choose to take a candy out of the candy box (assuming there is enough candy in the box) or put back a candy.
How many times does Xiao Ming need at least (take out, put back and distribute equally once) to distribute the candy in his hand to only one left
Enter a description:
Number of candies captured (<10000000000):
15
Output description:
Number of times to distribute at least one candy:
5
Example 1:
input
15
output
5
Remarks:
Interpretation: (1) 15+1=16; (2) 16/2 = 8; (3) 8/2 = 4; (4) 4/2 = 2; (5) 2/2 = 1;
Answer:
Solution 1:
import java.io.InputStream; import java.util.Scanner; public class Main { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(System.in); long sum = scanner.nextLong(); System.out.println(count(sum, 0)); } private static int count(long sum, int count){ if(sum <= 1){ return count; } if(sum%2==0){ return count(sum/2, count + 1); } return Math.min(count(sum + 1, count + 1), count(sum - 1,count + 1)); } }
15. Tall and short people queuing
Now there is a group of children who are different in height and height. We express the height of this group of children in positive integer array, such as array {5,3,1,2,3}.
We now want children to queue up in the order of "tall", "short", "tall", "short". Each "tall" position has a higher or equal number of children than its neighbors. The children in each "short" position are shorter or equal than their neighbors;
Ask the children to move the smallest distance and the first row starts from the "high" position and outputs the smallest distance.
For example, {5, 1, 3, 2, 3} is the sort result in the demonstration team {5, 3, 1, 2, 3}. {5, 2, 3, 1, 3} Although it also satisfies the order of "tall", "short", "high", "short", the movement distance of children is large, so it is not the optimal result.
The definition of the moving distance is as follows:
The second child moves behind the third child with a moving distance of 1. If the second child moves behind the fourth child, the moving distance is 2.
Enter a description:
Children before sorting, positive integer in English space:
4 3 5 7 8
Note: Kids <100
Output description:
Ordered children, positive integers separated by spaces in English:
4 3 7 5 8
Example 1:
input
4 1 3 5 2
output
4 1 5 2 3
Example 2:
input
1 1 1 1 1
output
1 1 1 1 1
Explain
Adjacent locations can be equal
Example 3:
input
xxx
output
[ ]
Explain:
Illegal parameter condition, returning empty array
Remarks:
4 (High) 3 (Short) 7 (High) 5 (Short) 8 (High), the output is the minimum moving distance, only 5 and 7 exchange positions, the moving distance is 1.
Answer:
Solution 1:
import java.util.Scanner; import java.util.LinkedList; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); LinkedList<Integer> list = new LinkedList<Integer>(); try { while (sc.hasNext()) { list.add(Integer.valueOf(sc.next())); } } catch (Exception e) { System.out.println("[]"); return; } for (int i = 0; i < list.size() - 1; i++) { if (i % 2 == 0 && Integer.valueOf(list.get(i)) < Integer.valueOf(list.get(i + 1))) { int tmp = list.get(i); list.set(i, list.get(i + 1)); list.set(i + 1, tmp); } else if (i % 2 == 1 && Integer.valueOf(list.get(i)) > Integer.valueOf(list.get(i + 1))) { int tmp = list.get(i); list.set(i, list.get(i + 1)); list.set(i + 1, tmp); } //System.out.print(str[i]); } for (int i = 0; i < list.size(); i++) { if (i != list.size() - 1) { System.out.print(list.get(i) + " "); } else { System.out.println(list.get(i)); } } } }
16. What if the work number is not enough?
With over 2 billion employees in 3020, Spatial Communications Group is facing the dilemma of not having enough work numbers.
Now, you are responsible for investigating the new number system. Inheriting the historical tradition, the new work numbering system consists of two parts: lowercase English letters (a-z) and numbers (0-9). The new number starts with an English letter, followed by a number such as "aaahw0001", "a12345", "abcd1", "a00". Note that the new number cannot be all letters or numbers, allowing leading zeros or all zeros in the numeric part.
However, a long work number increases the cost of memory for colleagues. Now give the number X that the new number needs to be assigned at least and the letter Y in the new work number, and find the shortest length Z of the number in the new number.
Enter a description:
Two non-negative integers, X Y, in a row, separated by a single space.
0< X <=2^50 - 1
0< Y <=5
Output description:
Output Minimum Length Z of Numbers in New Number
Example 1
input
260 1
output
1
Example 2
input
26 1
output
1
Explain
Number length cannot be zero
Example 3
input
2600 1
output
2
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long x = sc.nextLong(); int y = sc.nextInt(); int z = 1; int f = (int) Math.pow(26, y); while (f * Math.pow(10, z) < x) { z++; } System.out.println(z); } }
17. Pythagorean Arrays
If three positive integers (a,b,c) satisfy the relationship of a2 + b2 = c2, they are called (a,b,c) Pythagorean numbers (the well-known Pythagorean quadruplex five). To explore the law of Pythagorean numbers, we define that if there are two mutualities between Pythagorean numbers (a,b,c) (i.e., the two mutualities between a and b, A and c, B and c, with no common divisor), they are Pythagorean numeric ancestors (e.g. (3, 4, 5) are Pythagorean numeric ancestors. (6,8,10) is not a Pythagorean ancestor. Request all Pythagorean numeric ancestors within a given range [N,M].
Enter a description:
Start range N, 1 <= N <= 10000
End range M, N < M <= 10000
Output description:
- a,b,c Please ensure a < B < c, output format: a b c;
- Multiple groups of Pythagorean number ancestors, please sort the output in ascending order a, b, and finally c.
- Output "NA" if no Pythagorean ancestor is found in a given range.
Example 1:
input
1
20
output
3 4 5
5 12 13
8 15 17
Explain
The number of Pythagoreans in the range of [1, 20] is: (34 5), (5, 12, 13), (6, 8, 10), (8, 15), (9, 12, 15), (12, 16, 20); Among them, the primitive ancestors of Pythagorean numbers satisfying (a,b,c) the two reciprocal properties are: (34 5), (5 12 13), (8 15 17); Output results are required in the order described in the output.
Example 2:
input
5
10
output
NA
Explain
The number of Pythagoreans in the range of [5, 10] is: (68, 10); Among them, there is no Pythagorean number ancestor that satisfies the mutual quality between (a,b,c); No Pythagorean ancestor found in the given range, output "NA".
Answer:
Solution 1:
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static List solution(int N, int M){ List list = new ArrayList(); for(int i = N; i <= M - 2; i++){ for(int j = i + 1; j <= M - 1; j++){ double k = Math.sqrt(i * i + j * j); long kk = (long)k; if(k - kk == 0 && k <= M && help(i, j) && help(i, (int)(k)) && help(j, (int)(k))){ list.add(new int[]{i, j, (int)k}); }else if(k > M){ break; } } } return list; } public static boolean help(int l, int n){ if(l < n){ int temp = l; l = n; n = temp; } int p; while((p = l % n) != 0){ l = n; n = p; } return n == 1; } public static void main(String[] args){ Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int M = scanner.nextInt(); List<int[]> result = solution(N, M); if(result.size() > 0){ for(int[] res : result){ System.out.println(res[0] + " " + res[1] + " " + res[2]); } }else{ System.out.println("NA"); } } }
18. Number of shouts rearranged
Shout 7 is a traditional party game with N people in a circle numbered clockwise from 1 to N. One person with number 1 shouts from the beginning, and the next person adds 1 to the previous person's number, but when the number to be shouted is a multiple of 7 or if the number itself contains 7, you cannot shout the number directly, but you must shout "Yes". Assuming that none of the N people playing the game have missed the right time to shout "yes", when the number K is shouted, you can count the number of times that each person has shouted "yes".
Given an array with a length of N, which stores the number of times each person shouts "go" out of order, restore it to the correct order, that is, the number of times the person who stores the number i in the first element of the array shouts "go".
Enter a description:
Enter a line for the number of times you shout "past" separated by spaces. Note that K does not provide, K does not exceed 200, and the number of numbers is N.
Output description:
The output is a line, separated by spaces, for the correct number of times to shout "through".
Example 1:
input
0 1 0
output
1 0 0
Explain
There is only one shout "Yes" in total. That only happens when you need to shout 7. In order, people numbered 1 will encounter 7, so output 10. Note that the K at the end is not necessarily 7, it can be 8, 9, etc. The number of times you shouted is 100.
Example 2:
input
0 0 0 2 1
output
0 2 0 1 0
Explain
There are three times that people shout "Yes", which happens at 7 14 17. In order, people numbered 2 will encounter 7 17, and people numbered 4 will encounter 14, so output 0 20 1.
Answer:
Solution 1:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String s = reader.readLine(); String[] s1 = s.split(" "); int count = 0; for (int i = 0; i < s1.length; i++) { count += Integer.parseInt(s1[i]); } int num = 6; for (int j = 0; j < count; ) { num++; if(num % 7 == 0 || (num+"").contains("7")){ j ++; } } int[] arr = new int[s1.length]; for (int i = 1; i <= num; i++) { if(i % 7 == 0 || (i+"").contains("7")){ arr[i % s1.length]++; } } for (int i = 1; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.print(arr[0]); } }
19. Monkey Climbs Mountain
One day a stubborn monkey wants to climb from the foot of a hill to the top of a hill. On the way, it passes a ladder with N steps. But the monkey has a habit: it can only jump one step or three steps at a time. How many different ways can the monkey jump through this ladder?
Enter a description:
Enter a single integer N (0<N<=50) how many steps this ladder has
Output description:
Output how many skip modes (number of solutions)
Example 1:
input
50
output
122106097
Example 2:
input
3
output
2
Answer:
Solution 1:
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ int n = sc.nextInt(); Main m = new Main(); int sum = m.jump(n); System.out.print(sum); } } public int jump(int n){ if(n==1||n==2){ return 1; }else if(n==3){ return 2; }else{ return jump(n-3)+jump(n-1); } } }
20. Maximum sum of sliding windows
There is an array of N integers, and a window of length M. The window slides from the first number in the array until the window cannot slide. Each time the window slides, a window and (the sum of all the numbers in the window) are generated, and the maximum sum of all the windows produced by the window sliding is calculated.
Enter a description:
The first line enters a positive integer N, representing the number of integers. (0<N<100000)
The second line inputs N integers, which range from [-100,100].
The third line enters a positive integer M, M for window size, M<=100000, and M<=N.
Output description:
Maximum sum of all windows produced by window sliding.
Example 1:
input
6
10 20 30 15 23 12
3
output
68
Explain
The window length is 3, and the windows generated by window sliding are 10+20+30=60, 20+30+15=65, 30+15+23=68, 15+23+12=50, respectively, so the maximum sum of all windows generated by window sliding is 68.
Answer:
Solution 1:
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] array = new int[n]; for(int i = 0; i < n; i++){ array[i] = sc.nextInt(); } int m = sc.nextInt(); int sum=0; for(int i=0;i<m;i++){ sum+=array[i]; } int max = sum; if(n>m){ for(int i=0;i<(n-m);i++){ sum += (array[m+i]-array[i]); if(sum>max){ max=sum; } } } System.out.println(max); } }
21. Mars computing
The operators known to be used by Mars are #, KaTeX parse error: Expected'EOF', got'#'at position 18:... and the equivalent formula for Earth is as follows:x# ̲ y = 2*x+3*y+4...y = 3*x+y+2
1. where x and y are unsigned integers
2. The Earth Man formula is calculated according to C language rules
3. In the Martian formula, $takes precedence over #. The same operators are calculated from left to right
There is an existing Martian string message that you are asked to translate and calculate.
Enter a description:
Martian string expression (no carriage return at the end)
String description entered: The string is a calculation expression consisting of only unsigned integers and operators (#, $). For example: 123#4$5#67$78.
1. Use cases guarantee that there is no separator between operands and operators in the string.
2. Use cases guarantee that the range of operands is 32-bit unsigned integers.
3. Ensure that no integer overflow occurs in the input and calculation results.
4. Ensure that the input string is a valid evaluation message, for example, 123#4$5#67$78
5. Ensure that no illegal evaluation message occurs, such as a string like this:
#4$5 // missing operand
4$5# // missing operand
4#$5 //Missing operand
4 $5 // with spaces
3+4-5*6/7//with other operators
12345678987654321$54321//32-bit integer calculation overflow
Output description:
Output calculation results based on the input Mars string (no carriage return at the end)
Example 1
input
7#6$5#12
output
226
Explain
Example:
7#6$5#12
=7#(36+5+2)#12
=7#25#12
=(27+325+4)#12
=93#12
=293+3*12+4
=226
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // X#y = 2*x+3*y+4 x$y = 3*x+y+2 $Priority is higher than # while (sc.hasNextLine()) { String input = sc.nextLine(); System.out.print(func(input)); } sc.close(); } private static int func (String input) { //Prefer Last int index = input.lastIndexOf("#"); if (index!= -1) { String left = input.substring(0, index); String right = input.substring(index +1); int res = 2 * func(left) + 3 * func(right) + 4; return res; } // First priority index = input.lastIndexOf("$"); if (index != -1) { String left = input.substring(0, index); String right = input.substring(index +1); int res = 3 * func(left) + func(right) + 2; return res; } return Integer.parseInt(input); } }
22. Calculating area
The pen of the drawing machine is initially positioned at the origin (0, 0). When the machine starts, its pen draws a straight line according to the following rules:
1) Try to draw a straight line forward along the transverse axis until the given end value E.
2) During the offset period, the direction of the ordinate axis can be directed, and a straight line can be drawn at the same time. After the offset, a straight line can be drawn according to Rule 1. The format of the instruction is X offsetY, which means offset along the longitudinal direction in the horizontal coordinate X, positive offsetY for positive offset, and negative offset for negative offset.
Given the endpoint value E of the transverse coordinate and several drawing instructions, calculate the area where the drawn line and the transverse axis, and the line X=E, make up the graph.
Enter a description:
The first behavior is two integers, N E, indicating that there are N instructions, and the end value of the horizontal coordinate of the machine's operation, E.
Next N lines, two integers per line represent a drawing instruction, X offsetY, and the use case guarantees that the horizontal coordinates X appear in increasing order without the same horizontal coordinate X.
Value range: 0 < N <= 10000, 0 <= X <= E <= 20000, -10000 <= offsetY <= 10000.
Output description:
An integer representing the calculated area, guaranteed by the use case, with results ranging from 0 to 4294967295
Example 1:
input
4 10
1 1
2 1
3 1
4 -2
output
12
Example 2:
input
2 4
0 1
2 -2
output
4
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] a1 = sc.nextLine().split(" "); int count = Integer.valueOf(a1[0]); int total = Integer.valueOf(a1[1]); long result = 0; int last_x = 0, last_y = 0; for (int i = 0; i < count; i++) { String[] a2 = sc.nextLine().split(" "); int x = Integer.valueOf(a2[0]); int y = Integer.valueOf(a2[1]); result += (x - last_x) * Math.abs(last_y);; last_x = x; last_y += y; } result += (total - last_x) * Math.abs(last_y); System.out.println(result); } }
23. Calculate the maximum product
Given an array with an element type of lowercase string, calculate the maximum product of the length of two elements without the same character, and return 0 if there are no two elements that meet the criteria.
Enter a description:
Enter an array of lowercase character strings separated by a half-corner comma, 2 <=array length<=100, 0 <string length<= 50.
Output description:
The maximum value of the product of the length of two elements without identical characters.
Example 1
input
iwdvpbn,hk,iuop,iikd,kadgpf
output
14
Explain
There are five elements in the array.
Iwdvpbn and hk do not have the same characters, meet the conditions, iwdvpbn length is 7, hk length is 2, product is 14 (7*2).
iwdvpbn and iuop, iikd, kadgpf all have the same characters, which do not meet the conditions.
iuop has the same characters as iikd and kadgpf and does not meet the criteria.
iikd has the same characters as kadgpf and does not meet the criteria.
Therefore, the output is 14.
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int maxValue = -1; String a = in.nextLine(); if(a == null) { System.out.println(0); } String[] array = a.split(","); if(array.length == 1){ System.out.println(0); } for(int i = 0; i< array.length; i++) { for(int j = i+1; j< array.length; j++) { if(equals(array[i], array[j])){ int a1 = array[i].length(); int b = array[j].length(); maxValue = Math.max(maxValue, a1*b); } } } System.out.println(maxValue == -1? 0 : maxValue); } public static boolean equals(String a, String b) { for(int i = 0; i< a.length(); i++) { for(int j = 0; j< b.length(); j++) { if(a.charAt(i) == b.charAt(j)){ return false; } } } return true; } }
24. Check if there is a number combination that meets the criteria
Given a positive integer array, check the array for number combinations that satisfy the rules
Rules:
A = B + 2C
Enter a description:
Number of elements in the first line output array.
The next line outputs all array elements, separated by spaces.
Output description:
If there are numbers that meet the requirements, output values of A/B/C in the same line in turn, separated by spaces.
If not, output 0.
Example 1:
input
4
2 7 3 0
output
7 3 2
Explain
7 = 3 + 2 * 2
Example 2:
input
3
1 1 1
output
0
Explain
No combination found to meet the criteria
Remarks:
-
The length of the array is between 3 and 100.
-
Array members are 0-65535 and can be repeated, but each member can only be used once in the resulting formula. For example, if the array member is [0, 0, 1, 5], it is allowed that 0 occurs twice, but the result 0 = 0 + 2 * 0 is not allowed because there are 3 zeros used in the formula.
-
Use cases ensure that there is at most one set of satisfactory solutions in each set of numbers.
Answer:
Solution 1:
import java.util.Scanner; public class Main{ public static void main(String args[]){ Scanner s = new Scanner(System.in); while(s.hasNext()){ int length = s.nextInt(); int arr[] = new int [length]; for(int i=0;i<length;i++){ arr[i] = s.nextInt(); } sort(arr,0,length-1); int i; boolean end = false; for(i=0;i<length-1;i++){ for(int j=0;j<length-1;j++){ if(j==i) continue; int sum = arr[i]+arr[j]*2; if(sum>arr[length-1]) break; int max = i>j ? i : j; for(int k=max+1;k<length;k++){ if(sum == arr[k]){ System.out.println(arr[k]+" "+arr[i]+" "+arr[j]); end = true; break; } } if(end) break; } if(end) break; } if(i==length-1){ System.out.println(0); } } } static void sort(int arr[], int left, int right){ if(left>=right) return; int sign = arr[left]; int l = left; int r = right; while(l<r){ while(arr[r]>=sign && l<r) r--; arr[l] = arr[r]; while(arr[l]<=sign && l<r) l++; arr[r] = arr[l]; } arr[l] = sign; sort(arr,left,r); sort(arr,l+1,right); } }
25. Matrix Diffusion
There is a two-dimensional array of m*n whose members range from 0 to 1. Members with a value of 1 are diffusive, and after each 1S, members with a value of 0 are assimilated to 1. Members of a two-dimensional array have an initial value of 0. When the elements at [i,j] and [k,l] positions are modified to 1, it takes how long to find all the elements of the matrix to 1.
Enter a description:
The first two numbers in the output data indicate that this is an m*n matrix, and m and N will not exceed 1024 sizes. The middle two numbers indicate that an initial diffusion point location is i,j; The last two numbers indicate that the other diffusion point is k,l.
Output description:
It takes seconds for all elements of the output matrix to become one.
Example 1:
input
4,4,0,0,3,3
output
3
Explain
The first two numbers in the output data indicate that this is a 4*4 matrix. The middle two numbers represent an initial diffusion point location of 0,0. The last two numbers indicate that the other diffusion point is located at 3,3.
The example given is a very simple model where the initial point is diagonal and the middle position is reached by three iterations, that is, three seconds. So the output is 3.
26. Maximum Matrix
Given an N*N two-dimensional matrix containing only 0 and 1, calculate the maximum of the two-dimensional matrix with the following rules:
1. Each row of elements forms a binary number in subscript order (the larger the subscript, the lower the subscript), and the value of the binary number is the value of the row. The sum of each row of the matrix is the value of the matrix.
2. Allow each element to change its position in a row by moving it in a whole loop to the left or right.
For example, [1,0,1,1,1] moves 2 bits to the right of the overall cycle to become [1,1,1,0,1], the binary number is 11101, the value is 29.
[1,0,1,1,1]Moves 2 bits to the left of the overall loop to [1,1,1,0], with a binary number of 11110 and a value of 30.
Enter a description:
1. The first behavior of the input is a positive integer, recording the size of N, 0 < N <= 20.
2. The input 2-N+1 behaves as two-dimensional matrix information separated by commas at the corners of the elements in the row.
Output description:
Maximum value of the matrix.
Example 1:
input
5
1,0,0,0,1
0,0,0,1,1
0,1,0,1,0
1,0,0,1,1
1,0,1,0,1
output
122
Explain
Move the first row one bit to the right in the global loop to get the maximum value of the row [1,1,0,0,0], the binary value is 11000, and the decimal value is 24.
The second row moves 2 bits to the right in the overall loop to get the maximum value of the row [1,1,0,0,0], the binary value is 11000, and the decimal value is 24.
The third row moves one bit to the left in the overall loop to get the maximum value of the row [1,0,1,0,0], the binary value is 10100, and the decimal value is 20.
The fourth row moves 2 bits to the right in the overall loop to get the maximum value of the row [1,1,1,0,0], the binary value is 11100, and the decimal value is 28.
The fifth row moves one bit to the right in the global loop to get the maximum value of the row [1,1,0,1,0], the binary value is 11010, and the decimal value is 26.
Therefore, the maximum value of the matrix is 122.
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int count = sc.nextInt(); sc.nextLine(); String[] m = new String[count]; int result = 0; for (int i = 0; i < count; i++) { m[i] = sc.nextLine().replaceAll(",", ""); int max = 0; String v = m[i]; for (int j = 0; j < v.length(); j++) { if (max < Integer.parseInt(v, 2)) { max = Integer.parseInt(v, 2); } v = v.substring(1, v.length()) + v.substring(0, 1); } result += max; } System.out.println(result); } }
27. Attendance Information
The company uses a string to represent the employee's attendance information:
absent: absence
Late: late
leaveearly: leave early
present: normal work
Based on the attendance information of the employees, it is necessary to judge whether they can get the attendance prize or not. The following conditions can be used to get the attendance prize:
Absence not more than once; There is no continuous late/early departure; Any seven consecutive absences, absences/late/early departures no more than three times
Enter a description:
String of user's attendance data, number of records >= 1; The input string length is less than 10000; No illegal input exists
For example:
2
present
present absent present present leaveearly present absent
Output description:
According to the string of attendance data, if you get an attendance award, output "true"; Otherwise, output "false", the result for the input example should be:
true false
Example 1:
input
2
present
present present
output
true true
Example 2:
input
2
present
present absent present present leaveearly present absent
output
true false
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int cnt; cnt = Integer.parseInt(sc.nextLine()); String[] arr = new String[cnt]; for (int i = 0; i < cnt; i++) { String s = sc.nextLine(); arr[i] = s; } Main myTest = new Main(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < cnt; i++) { if (arr[i] == null || arr[i].length() == 0) break; String[] split = arr[i].split(" "); int absentCnt = 0; int lastLastOrEarly = -1; boolean flag = false; for (int j = 0; j < split.length; j++) { if ("absent".equalsIgnoreCase(split[j])) { absentCnt++; if (absentCnt >= 2) { sb.append("false "); flag = true; break; } } else if ("late".equalsIgnoreCase(split[j]) || "leaveearly".equalsIgnoreCase(split[j])) { if (lastLastOrEarly == -1) { lastLastOrEarly = j; } else { if (j - lastLastOrEarly == 1) { sb.append("false "); flag = true; break; } else lastLastOrEarly = j; } } boolean b = myTest.judge7C(split, j); if (!b) { sb.append("false "); flag = true; break; } } if (!flag) sb.append("true "); } System.out.println(sb.toString().trim()); } private boolean judge7C(String[] split, int now) { int cnt = 0; if (now < 7) { for (int i = 0; i <= now; i++) { String s = split[i]; if ("absent".equals(s) || "late".equals(s) || "leaveearly".equals(s)) { cnt++; } } } else { for (int i = now - 6; i <= now; i++) { String s = split[i]; if ("absent".equals(s) || "late".equals(s) || "leaveearly".equals(s)) { cnt++; } } } return cnt <= 3; } }
28. Pedestrian cars
Programmer Xiao Ming took a taxi to work. Due to occupational sensitivity, he noticed a problem with the taxi's billing table, which was always too large.
The taxi driver explained that he did not like the number 4, so he modified the billing table, skipped the number 4 at any number position, and the rest of the functions were normal.
For example:
-
23 One more dollar is 25;
-
39 One more dollar becomes 50;
-
399 One more dollar becomes 500;
Xiao Ming broke through the driver's tricks and was ready to use his knowledge to defeat the driver's conspiracy.
Gives surface readings of the billing table, returning the actual costs incurred.
Enter a description:
There is only one line, the number N, which represents the reading of the milemeter.
(1<=N<=888888888).
Output description:
A number that represents the actual cost incurred. End with return.
Example 1:
input
5
output
4
Explain
5 represents the surface reading of the billing table.
4 means that the cost actually incurred is only 4 Yuan.
Example 2:
input
17
output
15
Explain
17 represents the surface reading of the billing table.
15 means that the actual cost incurred is only 15 yuan.
Example 3:
input
100
output
81
Explain
100 represents the surface reading of the billing table.
81 means the cost actually incurred is only 81 yuan.
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int ans = n,temp = 0,k = 0,j = 1; while(n > 0){ if (n % 10 > 4){ temp += (n % 10 - 1) * k + j ; }else { temp += (n % 10) * k; } k = k * 9 + j; j *= 10; n /= 10; } System.out.println(ans - temp); } }
29. Express Transport
A delivery truck, which carries couriers, is packed in cuboxes of varying sizes. To be able to load more couriers without overloading the truck, you need to calculate the maximum number of couriers that can be loaded.
Note: The volume of the courier is unlimited, the maximum number of couriers is 1000, and the maximum truck load is 50000.
Enter a description:
The first line enters the weight of each courier, separated by English commas, e.g. 5,10,2,11
The second line enters the load weight of the truck, for example:20
There is no need to consider exceptional input.
Output description:
The maximum number of couriers that can be loaded in the output, such as: 3
Example 1:
input
5,10,2,11
20
output
3
Explain
The truck can only carry up to three Express 5, 10, 2 with a load of 20, so the output is 3
Answer:
Solution 1:
import java.util.*; public class Main { public static void main(String args[]) { Scanner input = new Scanner(System.in); String s = input.nextLine(); //Express Weight Separated by English Commas int w = input.nextInt(); //Truck weight String[] split = s.split(","); List list = new LinkedList<Integer>(); for (int i=0;i<split.length;i++){ list.add(Integer.valueOf(split[i])); } int minNum; int count = 0; while (true){ minNum = 100000; //Find the Minimum for (int i=0;i<list.size();i++){ if (minNum>(Integer) list.get(i)){ minNum = (Integer) list.get(i); } } list.remove(Integer.valueOf(minNum)); if (w-minNum<0){ break; } w = w-minNum; count++; } System.out.println(count); } }
30. Continuous letter length
Given a string that contains only uppercase letters, find the length of the k-long substring among the substrings that contain the same letter, taking only the longest substring for the same letter.
Enter a description:
The first line has a substring (1<length<=100) that contains only uppercase letters.
The value of the second behavior k
Output description:
Output the number of consecutive occurrences of the most k letters.
Example 1
input
AAAAHHHBBCDHHHH
3
output
2
Explain
The highest number of consecutive occurrences of the same letter is A and H, four times. The second most is H, three times, but H already has four consecutive, so it is not considered; The next longest substring is BB, so the final answer should output 2.
Example 2
input
AABAAA
2
output
1
Explain
The highest number of consecutive occurrences of the same letter is A, three times; The second most is A, twice, but A already has the maximum number of consecutive times three times, so it is not considered; The next longest substring is B, so output 1
Example 3
input
ABC
4
output
-1
Explain
Only three substrings with the same letter, less than k, output-1
Example 4
input
ABC
2
output
1
Explain
All three substrings have a length of 1, so in this case k = 1, k=2, k=3 all output 1. Hereby, to avoid ambiguity.
Remarks:
Output-1 if the number of substrings containing only the same letter is less than k
Answer:
Solution 1:
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); while(sc.hasNext()){ String s = sc.next(); int k=sc.nextInt(); char[] cArray=s.toCharArray(); Map<Character,Integer> map=new HashMap<>(); Set<Character> set=new HashSet<>(); map.put(cArray[0],1); for(int i=0;i<cArray.length;i++){ int start=i; while(start+1<cArray.length && cArray[start]==cArray[start+1]){ start++; } char c=cArray[i]; set.add(c); int time=map.getOrDefault(c,0); if(start-i+1>time){ map.put(c,start-i+1); } i=start; } List<Integer> list=new ArrayList<>(); for(Character c:set){ list.add(map.get(c)); } list.sort((n1,n2)->n2-n1); if(k-1<list.size() && k>0){ System.out.println(list.get(k-1)); }else{ System.out.println(-1); } } } }
31. Minimum absolute value of sum of two numbers
Given an ordered sequence of integers (positive and negative integers) nums from smallest to largest, find out in the array that the absolute value of the sum of two numbers (|nums[x]+nums[y]|) is the minimum and return this absolute value.
Each input corresponds to only one answer. However, the same element in an array cannot be used twice.
Enter a description:
A sequence of ordered integers separated by spaces, up to 1000 integers, with integer values ranging from -65535 to 65535.
Output description:
Minimum absolute value of sum of two numbers
Example 1
input
-3 -1 5 7 11 15
output
2
Explain
Returns 2 because |nums[0] + nums[2]| = |-3 + 5| = 2 is the smallest
Answer:
Solution 1:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; while ((str=br.readLine())!=null) { String[] nums=str.split(" "); int minNum=Integer.MAX_VALUE; for(int i=0;i<nums.length-1;i++){ for(int j=i+1;j<nums.length;j++){ int temp=Math.abs((Integer.valueOf(nums[i])+Integer.valueOf(nums[j]))); if(minNum>temp){ minNum=temp; } } } System.out.println(minNum); } } }
32. Pipeline
A factory has m pipelines to complete n independent jobs in parallel. The factory has a scheduling system that always gives priority to the jobs with the shortest processing time when scheduling jobs.
Given the number of pipelines m, the number of jobs n that need to be completed, and the processing time of each job is t1,t2...tn, respectively. How long does it take you to program all your jobs?
When n>m, the shortest m jobs are processed first into the pipeline, while the others wait. When a job is completed, the shortest processing time is taken from the remaining jobs in turn into the processing.
Enter a description:
The first behavior consists of two integers (separated by spaces) representing the number of pipelines m and the number of jobs n, respectively.
The second line enters n integers (separated by spaces) representing the processing time t1,t2...tn for each job.
0< m,n<100,0<t1,t2...tn<100.
Note: Ensure that all inputs are legitimate.
Output description:
Total length of time the output has processed all jobs
Example 1
input
3 5
8 4 3 2 10
output
13
Explain
1. Schedule three jobs with time 2, 3 and 4 first.
2. The first pipeline finishes the job first, and then schedules job 8 with the shortest remaining time.
3. The second pipeline finishes the job and then schedules the job with the shortest remaining time.
4. The total work time is 13 (3+10) for the second pipeline to complete the operation.
Answer:
Solution 1:
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int m=sc.nextInt(); //Assembly line int n=sc.nextInt();//Number of jobs int time[]=new int[n]; for(int i=0;i<n;i++){ time[i]=sc.nextInt(); } System.out.println(caculate(m,n,time)); } public static int caculate(int m,int n,int time[]){ Arrays.sort(time); int sum[]=new int[m]; //M pipelines, m results, Max for(int i=0;i<n;i++){ sum[i%m]+=time[i]; } int res=0; for(int j=0;j<m;j++){ res=Math.max(res,sum[j]); } return res; } }
33. The absolute value of the sum of two numbers in a random integer sequence is the smallest
Given a random integer (possibly positive and negative integers) array nums, find two numbers in the array whose absolute value of the sum (|nums[x]+nums[y]|) is the minimum, and return the two numbers (from small to large) as well as the absolute value.
Each input corresponds to only one answer. However, the same element in an array cannot be used twice.
Enter a description:
A sequence of ordered integers separated by spaces, up to 1000 integers, with integer value ranges of [-65535, 65535].
Output description:
Minimum absolute value of sum of two numbers
Example 1
input
-1 -3 7 5 11 15
output
-3 5 2
Explain
Because |nums[0] + nums[2]| = |-3 + 5| = 2 is the smallest, it returns -3 5 2
Answer:
Solution 1:
import java.util.ArrayList; import java.util.Comparator; import java.util.Scanner; public class Main { public static void main(String[] args) { int total = 65535 * 2;// Records and Absolute Values int[] index = new int[2];// Number array subscript after record sorting Scanner sc = new Scanner(System.in); String dataList = sc.nextLine(); // Converts a numeric string to a numeric array and sorts it String[] strArr = dataList.split(" "); ArrayList<Integer> dataNewList = new ArrayList<Integer>(); for (int i = 0; i < strArr.length; i++) { dataNewList.add(Integer.valueOf(strArr[i])); } dataNewList.sort(Comparator.naturalOrder());// Ascending order // Bubble record and absolute minimum for (int i = 0; i < dataNewList.size(); i++) { for (int j = i + 1; j < dataNewList.size(); j++) { int temp = Math.abs(dataNewList.get(i) + dataNewList.get(j)); if (temp <= total) { total = temp; index[0] = i; index[1] = j; } } } System.out.println(dataNewList.get(index[0]) + " " + dataNewList.get(index[1]) + " " + total); } }
34. Memory Resource Allocation
There is a simple memory pool with memory sorted by size and granularity, and there are several available memory resources at each granularity. Users make a series of memory requests and need to allocate the resources in the memory pool on demand to return a list of successful and failed requests. The allocation rules are as follows:
1. Allocated memory is greater than or equal to the amount of memory requests. Memory that meets the needs must be allocated. Priority allocation is small in granularity, but memory cannot be split for use.
2. It needs to be allocated in the order of application, the first allocation being the application.
3. If there is an available memory allocation, the result is true, and if there is no available memory allocation, false is returned.
Note: Memory release is not considered.
Enter a description:
The input is a two-line string:
The first behavior is a list of memory pool resources, which contains information about memory granularity data, which is separated by commas, one granularity information is separated by colons internally, the size of memory granularity before the colon, and the number after the colon. Resource lists are not greater than 1024, and the number of granularities is not greater than 4096
The second behavior is the application list, where the memory size of the application is separated by commas. Application list is no more than 100000
For example:
64:2,128:1,32:4,1:128
50,36,64,128,127
Output description:
Output is the result of memory pool allocation.
For example:
true,true,true,false,false
Example 1
input
64:2,128:1,32:4,1:128
50,36,64,128,127
output
true,true,true,false,false
Explain
Memory pool resources include: 64K 2, 128K 1, 32K 4, 1K 128;
For the memory request sequence of 50,36,64,128,127, the allocated memory is 64,64,128,NULL,NULL, 128 has been allocated for the third time,
So the output is true,true,true,false,false
Answer:
Solution 1:
import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String mem = scanner.nextLine(); String app = scanner.nextLine(); String[] mems = mem.split(","); String[] apps = app.split(","); if (mems.length > 1024 || apps.length >100000) return; Map<Integer,Integer> map = new LinkedHashMap<>(); for (int i = 0;i<mems.length;i++){ String[] tmp = mems[i].split(":"); if (Integer.parseInt(tmp[1]) > 4096) return; map.put(Integer.parseInt(tmp[0]),Integer.parseInt(tmp[1])); } for (int i = 0;i<apps.length;i++){ if (i > 0){ System.out.print(","); } List<Integer> list = new ArrayList<>(); for (Integer integer : map.keySet()){ if (integer >= Integer.parseInt(apps[i])){ list.add(integer); } } if (list.size() > 0){ Integer a = map.get(Collections.min(list)); a = a - 1; if (a == 0){ map.remove(Collections.min(list)); }else{ map.put(Collections.min(list),a); } System.out.print("true"); }else{ System.out.print("false"); } } } }
35. Determine whether a set of inequalities satisfies constraints and outputs the maximum difference
Given a set of inequalities, the maximum difference (the integer part of the output floating-point number) of inequalities is determined whether they are valid or not, requiring that: 1) the coefficient of inequality is of type double and is a two-dimensional array; 2) The variable of inequality is of type int and is a one-dimensional array; 3) The target value of the inequality is a double type, which is a one-dimensional array. 4) Inequality constraints are string arrays, which can only be:'>', >=', <, <=', =', for example, group of inequalities:
a11x1+a12x2+a13x3+a14x4+a15x5<=b1;
a21x1+a22x2+a23x3+a24x4+a25x5<=b2;
a31x1+a32x2+a33x3+a34x4+a35*x5<=b3;
Maximum difference = max{(a11x1+a12x2+a13x3+a14x4+a15x5-b1), (a21x1+a22x2+a23x3+a24x4+a25x5-b2), (a31x1+a32x2+a33x3+a34x4+a35*x5-b3)}, type is integer (integer part of output floating point number)
Enter a description:
1) Inequality group factor (double type):
a11,a12,a13,a14,a15
a21,a22,a23,a24,a25
a31,a32,a33,a34,a35
2) Inequality variable (int type):
x1,x2,x3,x4,x5
3) Inequality Target Value (double Type):b1,b2,b3
4) Inequality constraints (string type): <=, <=, <=
Input: a11, a12, a13, a14, a15; A21, a22, a23, a24, a25; A31, a32, a33, a34, a35; X1, x2, x3, x4, x5; B1, b2, b3; <=, <=, <=
Output description:
true or false, maximum difference
Example 1
input
2.3,3,5.6,7,6;11,3,8.6,25,1;0.3,9,5.3,66,7.8;1,3,2,7,5;340,670,80.6;<=,<=,<=
output
false 458
Example 2
input
2.36,3,6,7.1,6;1,30,8.6,2.5,21;0.3,69,5.3,6.6,7.8;1,13,2,17,5;340,67,300.6;<=,>=,<=
output
false 758
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { double [][] a = new double[3][5]; int [] x = new int[5]; double [] b = new double[3]; String [] eqExpression = new String[3]; int [] resultArrTemp = new int[3]; int max = 0; Scanner scanner = new Scanner(System.in); boolean result = true; String lines = scanner.nextLine(); String [] line = lines.split(";"); //int i; for (int i = 0; i < 3; i++) { String [] temp1 = line[i].split(","); for (int j = 0; j < 5; j++) { a[i][j] = Double.valueOf(temp1[j]); } } String [] temp2 = line[3].split(","); for (int i = 0; i < 5; i++) { x[i] = Integer.valueOf(temp2[i]); } String [] temp3 = line[4].split(","); for (int i = 0; i < 3; i++) { b[i] = Double.valueOf(temp3[i]); } String [] temp4 = line[5].split(","); for (int i = 0; i < 3; i++) { eqExpression[i] = temp4[i]; } for (int i = 0; i < 3; i++) { double temp=0.0; for (int j = 0; j < 5; j++) { temp = temp + a[i][j]*x[j]; } if ("<=".equals(eqExpression[i])){ if (temp<=b[i]){ result = result && true; resultArrTemp[i] = (int) ((temp-b[i])/1); }else{ result = result && false; resultArrTemp[i] = (int) ((temp-b[i])/1); } } else if ("<".equals(eqExpression[i])) { if (temp<b[i]){ result = result && true; resultArrTemp[i] = (int) ((temp-b[i])/1); }else{ result = result && false; resultArrTemp[i] = (int) ((temp-b[i])/1); } } else if ("=".equals(eqExpression[i])) { //String tempStr1 = String.valueOf(temp); //String tempStr2 = String.valueOf(b[i]); if (temp==b[i]){ result = result && true; resultArrTemp[i] = (int) ((temp-b[i])/1); }else{ result = result && false; resultArrTemp[i] = (int) ((temp-b[i])/1); } } else if (">".equals(eqExpression[i])) { if (temp>b[i]){ result = result && true; resultArrTemp[i] = (int) ((temp-b[i])/1); }else{ result = result && false; resultArrTemp[i] = (int) ((temp-b[i])/1); } } else if (">=".equals(eqExpression[i])) { if (temp>=b[i]){ result = result && true; resultArrTemp[i] = (int) ((temp-b[i])/1); }else{ result = result && false; resultArrTemp[i] = (int) ((temp-b[i])/1); } } } for (int i = 0; i < 3; i++) { if (i==0){ max = resultArrTemp[i]; } if (resultArrTemp[i]>=max){ max = resultArrTemp[i]; } } System.out.println(result+" "+max); } }
36. Judging Subsequence of Strings
Given the strings target and source, determine if the target is a subsequence of the source.
You can think that target and source contain only lowercase letters. The string source may be long (length ~= 500,000), while the target is a short string (length <=100).
A subsequence of a string is a new string formed by the original string deleting some (or no) characters without changing the relative position of the remaining characters. (For example, "abc" is a subsequence of "aebycd" and "ayb" is not).
Find the starting position of the last subsequence.
Enter a description:
The first behavior is target, short string (length <=100)
The second behavior is source, long string (length ~= 500,000)
Output description:
The starting position of the last subsequence, the subscript of the first letter of the last subsequence
Example 1
input
abc
abcaybec
output
3
Explain
Here there are two subsequences of abc satisfied, the larger the subscript, so return 3
Remarks:
Output-1 if target is not found in source
Answer:
Solution 1:
import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); char[] tChars = scanner.nextLine().toCharArray(); char[] sChars = scanner.nextLine().toCharArray(); LinkedHashMap<Character, Integer> characterIntegerLinkedHashMap = new LinkedHashMap<Character, Integer>(); int des=sChars.length; if (tChars.length>0&&sChars.length>0) { for (int j = tChars.length - 1; j >= 0; j--) { for (int i = sChars.length - 1; i >= 0; i--) { if (tChars[j] == sChars[i] & des > i) { des = i; characterIntegerLinkedHashMap.put(tChars[j], i); break; } } } int ros = 0; for (int j = tChars.length - 1; j >= 0; j--) { if (!characterIntegerLinkedHashMap.containsKey(tChars[j])) { ros = -1; break; } } if (ros != -1) { System.out.println(characterIntegerLinkedHashMap.get(tChars[0])); } else { System.out.println(ros); } }else { System.out.println(-1); } } }
37. Stitching URL s
Given a URL prefix and a URL suffix, split by','it needs to be connected to a complete URL. If there is no'/' at the end of the prefix and at the beginning of the suffix, the'/'connector needs to be automatically appended. If both the end of the prefix and the beginning of the suffix are'/', it needs to be automatically de-duplicated.
Constraint: Do not consider illegal prefix URL s.
Enter a description:
The URL prefix (a string less than 100) and the URL suffix (a string less than 100).
Output description:
Split URL.
Example 1
input
/acm,/bb
output
/acm/bb
Example 2
input
/abc/,/bcd
output
/abc/bcd
Example 3
input
/acd,bef
output
/acd/bef
Example 4
input
,
output
/
Answer:
Solution 1:
// This is an example of the specification for single-line and multiple-line input and output of an exam. It does not require submission and does not score. import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextLine()) {// Note that if the input is multiple test cases, use the while loop to process multiple test cases String inStr = in.nextLine(); String out = inStr.replaceFirst(",", "/"); out = out.replace("//", "/"); out = out.replace("//", "/"); System.out.println(out); } } }
38. Ways of pairing to meet the requirements
Using an array A to represent the programmer's ability to work, the company wants to improve the employee's ability by pair programming. Assuming the ability after pairing is the sum of the two employee's ability, find out how many pairing methods make the pairing ability N.
Enter a description:
5
1 2 2 2 3
4
Total number of employees in the first act, value range [1,1000]
Elements of the second behavior array A, with a range of values for each element [1,1000]
The third behavior is the value of N, in the range [1,1000]
Output description:
4
Total number of pairing modes that satisfy the pairing capability of N
Example 1
input
5
1 2 2 2 3
4
output
4
Explain
The required pairing methods are A[0] and A[4], A[1] and A[2], A[1] and A[3], A[2] and A[3]
Answer:
Solution 1:
import java.util.*; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int total = sc.nextInt(); int[] person = new int[total]; for (int i = 0; i < total; i++) { person[i] = sc.nextInt(); } int sum = sc.nextInt(); int ans = 0; for (int i = 0; i < total; i++) { int persona = person[i]; for (int j = i + 1; j < total; j++) { int personb = person[j]; if (sum == persona + personb) { ans++; } } } System.out.println(ans); } }
39. Solving Continuous Sequences
Known continuous positive integer column {K}=K1,K2,K3...K I adds up to S, i=N (0<S<100000, 0<N<100000), and evaluates this column K.
Enter a description:
The input contains two parameters, 1) the number of miles in the continuous positive integer column and S,2) number column, N.
Output description:
If there is a solution output column K, if there is no solution output-1
Example 1
input
525 6
output
85 86 87 88 89 90
Example 2
input
3 5
output
-1
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int sum = in.nextInt(); int n = in.nextInt(); // sum(x x+1 x+2 ... x+n-1) = sum // n*x + n*(n-1)/2 = sum // x= [sum - n*(n-1)/2 ]/n int temp = sum - n*(n-1)/2; if (temp <=0 || temp%n!=0){ System.out.println(-1); return; } int begin = temp/n; for (int i = 0; i < n; i++) { System.out.print(begin+i); System.out.print(' '); } } }
40. Find the minimum sum of all integers in the string
Input string s, output s contains the minimum sum of all integers
Explain
- String s, containing only a-z A-Z+;
- Legal integers include
1) Positive integers consisting of one or more 0-9, such as 0 2 3 002 102
2) Negative integer minus sign-start, where the number part consists of one or more 0-9, e.g. -0-012-23-00023
Enter a description:
String containing numbers
Output description:
Minimum sum of all integers
Example 1
input
bb1234aa
output
10
Example 2
input
bb12-34aa
output
-31
Explain
1+2+(-34) = 31
Answer:
Solution 1:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { // Calculates the minimum sum of all integers in the string, including a-z+-; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = br.readLine(); char[] chars = input.toCharArray(); char tmpChar; long sum = 0; // Marker for negative numbers boolean flag = false; StringBuilder sb = new StringBuilder(); for (int i = 0; i < chars.length; i++) { tmpChar = chars[i]; // Judgement characters 0-9 - if ('0' <= tmpChar && tmpChar <= '9') { if (flag) { // Minus the maximum negative number sb.append(tmpChar); } else { // Add a digit integer sum += Long.parseLong(tmpChar + ""); } } else if ('-' == tmpChar) { if (flag) { if (!sb.toString().isEmpty()) { sum -= Long.parseLong(sb.toString()); sb = new StringBuilder(); } } flag = true; } else { flag = false; if (!sb.toString().isEmpty()) { sum -= Long.parseLong(sb.toString()); sb = new StringBuilder(); } } } if (flag) { if (!sb.toString().isEmpty()) { sum -= Long.parseLong(sb.toString()); } } System.out.println(sum); } }
41. Seek how many teams can be dispatched at most
Use an array to represent each person's abilities. A competition activity requires a minimum competency value of N for the participating teams. Each team can be composed of one or two people, and only one person can participate in one team. Please calculate the maximum number of teams that can be dispatched to meet the requirements?
Enter a description:
5
3 1 5 7 9
8
The first row array represents the total number, range [1,500000]
The second row array represents everyone's capabilities, the range of values for each element [1,500000], the range of size for the array [1,500000]
The third line is the minimum competency required by the team, in the range [1,500000]
Output description:
3
Maximum number of teams that can be dispatched
Example 1
input
5
3 1 5 7 9
8
output
3
Explain
3,5 form a team, 1,7 form a team, 9 own teams, so output 3
Answer:
Solution 1:
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] nums = new int[n]; for (int i = 0; i < n; i++) { nums[i] = in.nextInt(); } int tar = in.nextInt(); int res = 0; Arrays.sort(nums); int left = 0; int right = n-1; while (nums[right]>tar){ right--; res++; } while (left<right){ //Two-person team if (nums[left]+nums[right]>=tar){ res++; right--; } left++; } System.out.println(res); } }
42. Delete the least characters in a string
Deletes the character that occurs least often in a string and deletes all characters if they occur the same number of times.
Enter a description:
Enter abcdd
The string contains only lowercase English letters.
Output description:
dd
Example 1
input
abcdd
output
dd
Example 2
input
aabbccdd
output
empty
Explain
If the characters of the string are deleted, the range empty
Answer:
Solution 1:
import java.util.*; public class Main { public static void main (String[] args) { Scanner scanner = new Scanner(System.in); String text = scanner.nextLine(); char[] chars = text.toCharArray(); Map<Character, Integer> char2times = new HashMap<>(10); for(int i = 0; i < chars.length; i++){ if(char2times.containsKey(chars[i])){ char2times.replace(chars[i], char2times.get(chars[i]) + 1); }else{ char2times.put(chars[i], 1); } } int minTimes = Integer.MAX_VALUE; List<Character> minTimesChars = new ArrayList<>(5); for(Character character : char2times.keySet()){ if(char2times.get(character) < minTimes){ minTimes = char2times.get(character); minTimesChars.clear(); minTimesChars.add(character); }else if(char2times.get(character) == minTimes){ minTimesChars.add(character); } } for (Character minTimesChar : minTimesChars) { text = text.replaceAll(minTimesChar.toString(),""); } System.out.println("".equals(text) ? "empty" : text); } }
43. Data Classification
Classify a data a by adding four bytes of this data a (four byte size) to modular a given value b. If the result is less than a given value c, data a is a valid type and its type is the modular value. If the result is greater than or equal to c, data a is an invalid type.
For example, a data a=0x010101, b=3, according to the classification method (0x01+0x01+0x01+0x01)%3=1, so if c=2, this a is a valid type, its type is 1, if c=1, it is an invalid type;
Another example is a data a=0x010103, b=3, which is calculated by classification method (0x01+0x01+0x01+0x03)%3=0, so if c=2, this a is a valid type, its type is 0, and if c=0, it is an invalid type.
Enter 12 data, the first data is c, the second data is b, and the remaining 10 data are data to be classified. Find the type with the most data in the valid type and output how many data the type contains.
Enter a description:
Enter 12 data separated by spaces, the first data being c, the second data being b, and the remaining 10 data being classified.
Output description:
How many data are output for the most valid type of data.
Example 1
input
3 4 256 257 258 259 260 261 262 263 264 265
output
3
Explain
The result of adding 4 bytes of 10 data is 12 3 4 5 6 7 8 9 10, so the result of modelling 4 is 12 3 0 1 2 3 1 2, c 3, so 0 12 is all valid types, types 1 and 2 have 3 data, types 0 only have 2 data, so output 3
Example 2
input
1 4 256 257 258 259 260 261 262 263 264 265
output
2
Explain
The result of adding 4 bytes of 10 data is 12 3 4 5 6 7 8 9 10, so the result of modularizing 4 is 12 3 0 1 2 3 1 2, c 1, so only 0 is a valid type, there are 2 data of type 0, so output 2
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { // Get data int c = sc.nextInt(); int b = sc.nextInt(); final int size = 10; int[] num = new int[size]; for (int i = 0; i < size; i++) { num[i] = sc.nextInt(); } // Typee records 10 valid type s, invalid records-1 int[] type = new int[size]; // Calculate valid types for (int i = 0; i < size; i++) { type[i] = getValidType(num[i], b, c); // System.out.print(i + "=" + type[i] + ", "); } // Number of data with the most calculation types int maxCount = 0; int count = 0; for (int i = 0; i < c; i++) { count = 0; for (int k = 0; k < size; k++) { if (i == type[k]) { count++; } } if (count > maxCount) { maxCount = count; } } // Output Results System.out.println(maxCount); } } private static int getValidType(int num, int b, int c) { // int converted to 4 bytes plus int sum = 0; for (int i = 0; i < 4; i++) { sum += num % 256; num /= 256; } int mod = sum % b; return mod < c ? mod : -1; } }
44. Sequence description
There is a column a[N] (N=60), starting with a[0], where each item is a number. a[n+1] in the column is the description of a[n]. Where a[0]=1.
The rules are as follows:
a[0]:1
A[1]: 11 (meaning: its previous item a[0]=1 is a 1, that is, "11". It means that a[0] appears from left to right once in a row.
A[2]: 21 (Meaning: its preceding item a[1]=11, from left to right: consists of two 1s,'21'. means that a[1] appears from left to right twice in a row.
A[3]: 1211 (meaning: its preceding item a[2]=21, from left to right: consists of one 2 and one 1, i.e.'1211'. means that a[2] appears from left to right once in a row,'2', and then one in a row)
A[4]: 111221 (meaning: its previous item a[3]=1211, from left to right: is composed of one 1, one 2, two 1, namely "111221". means that a[3] from left to right appears once in a row, "1", once in a row, "2", twice in a row)
Please output the nth result of this column (a[n], 0 < n < 59).
Enter a description:
The n-th item of the number column (0 < n < 59):
4
Output description:
Content of the column:
111221
Example 1
input
4
output
111221
Answer:
Solution 1:
import java.util.Scanner; public class Main{ public static void main(String[] args){ int count=new Scanner(System.in).nextInt()+1; String[] raw = new String[count]; raw[0]="1"; for(int i=1;i<count;i++){ StringBuilder builder=new StringBuilder(); char[] lastStr=raw[i-1].toCharArray(); char now=lastStr[0]; int charCount=1; int index=1; while(index<lastStr.length){ if(lastStr[index]==now) charCount++; else{ builder.append(charCount).append(now); now = lastStr[index]; charCount=1; } index++; } builder.append(charCount).append(now); raw[i]=builder.toString(); } System.out.println(raw[count-1]); } }
45. Digital Painting
After the epidemic, I hope that the primary school will finally reopen. The task of the first day of the second class of three years is to reproduce the blackboard newspapers that follow. N positive integers have been written on the blackboard. The students need to color each number separately. In order to make the blackboard newspaper both beautiful and meaningful for learning, the teacher asked that all numbers of the same color be divisible by the smallest number in that color. Now let's ask you to help the children figure out how many colors are needed to color the N numbers.
Enter a description:
The first line has a positive integer N, where 1 \leq N leq 1001 leq 1001 is not greater than or equal to N 100.
The second line has N integers (guaranteed to be in the [1,100] range) representing the values of each positive integer on the blackboard.
Output description:
The output has only one integer, which is the minimum number of colors required.
Example 1
input
3
2 4 6
output
1
Explain
All numbers can be divided by 2
Example 2
input
4
2 3 4 9
output
2
Explain
2 and 4 apply a color, 4 can be divided by 2; 3 and 9 are coated in another color, and 9 can be divided by 3. You cannot apply the same color to four numbers because 3 and 9 cannot be divided by 2. So there are two minimum colors.
Answer:
Solution 1:
import com.sun.imageio.plugins.common.I18N; import java.util.*; import java.util.stream.Collectors; public class Main { public static void main(String [] args){ Scanner input = new Scanner(System.in); Map<Integer,List<Integer>> result = new HashMap<>(); List<Integer> numList = new ArrayList<>(); while(input.hasNext()){ Integer N = input.nextInt(); for(int i=0;i<N;i++){ numList.add(input.nextInt()); } numList = numList.stream().sorted().collect(Collectors.toList()); for(int i =0;i<numList.size();i++){ if(i==0){ List<Integer> singleList = new ArrayList<>(); singleList.add(numList.get(i)); result.put(numList.get(i),singleList); }else{ List<Map.Entry<Integer,List<Integer>>> mapList = result.entrySet().stream().collect(Collectors.toList()); for(int j=0;j<mapList.size();j++){ if(numList.get(i)%mapList.get(j).getKey()==0){ result.get(mapList.get(j).getValue().add(numList.get(i))); break; }else { if(j==mapList.size()-1){ List<Integer> singleList = new ArrayList<>(); singleList.add(numList.get(i)); result.put(numList.get(i),singleList); } } } } } System.out.println(result.size()); } } }
46. Array Binary Tree
Binary trees can also be stored in arrays. Given an array, the value of the root node of the tree is stored in subscript 1. For a node stored in subscript N, its left and right children are stored in subscript 2N and 2N+1, respectively, and we use value-1 to represent a node that is empty.
Given a binary tree stored in an array, try to find the path from the root node to the smallest leaf node, which consists of the values of the nodes.
Enter a description:
Enter the contents of an array of rows, each element of which is a positive integer separated by spaces. Notice that the first element is the value of the root node, that is, the Nth element of the array corresponds to the subscript N, and the subscript 0 is not used in the representation of the tree, so we omitted it. The maximum number of trees entered is 7.
Output description:
Output path from root node to minimum leaf node, values of each node are separated by spaces, and use case ensures that there is only one minimum leaf node.
Example 1
input
3 5 7 -1 -1 2 4
output
3 7 2
Explain
The binary tree stored in the array is shown, so the path to the smallest leaf node is 372
Example 2
input
5 9 8 -1 -1 7 -1 -1 -1 -1 -1 6
output
5 8 7 6
Explain
The binary tree stored in the array is shown in the figure, so the path to the smallest leaf node is 101876. Note that the array is only stored to the last non-empty node, so it does not contain -1 of the right child node of node "7"
Answer:
Solution 1:
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); ArrayList<Integer> array = new ArrayList<>(); while (in.hasNextInt()) { array.add(in.nextInt()); } fun(array); } private static int dfs(List<Integer> nums, int index) { if (isLeaf(nums, index)) { return index; } else { int i1 = dfs(nums, 2 * index + 1); int i2 = dfs(nums, 2 * index + 2); if (i1 >= nums.size() || nums.get(i1) == -1) { return i2; } else if (i2 >= nums.size() || nums.get(i2) == -1) { return i1; } else { return nums.get(i1) < nums.get(i2) ? i1 : i2; } } } private static boolean isLeaf(List<Integer> nums, int index) { return (2 * index + 1 >= nums.size() || nums.get(2 * index + 1) == -1) && (2 * index + 2 >= nums.size() || nums.get(2 * index + 2) == -1); } private static void fun(List<Integer> nums) { int index = dfs(nums, 0); ArrayList<Integer> arr = new ArrayList<>(); while (index > 0) { arr.add(nums.get(index)); index = (index - 1) / 2; } arr.add(nums.get(0)); Collections.reverse(arr); for (Integer integer : arr) { System.out.print(integer + " "); } } }
47. Array Stitching
There are now multiple arrays of integers that need to be merged into a new array. Merge rule, which merges the fixed-length contents of each array sequentially into a new array, deletes the contents, and if the line is not long enough or empty, puts the contents of the remaining parts directly into a new array and proceeds to the next line.
Enter a description:
The first line is a fixed length per read, 0<length<10
The second line is the number of integer arrays, 0 < number < 1000
Rows 3-n are arrays that need to be merged, with different arrays separated by a carriage return line break and arrays separated by commas inside, up to a maximum of 100 elements.
Output description:
Output a new array, separated by commas.
Example 1
input
3
2
2,5,6,7,9,5,7
1,7,4,3,4
output
2,5,6,1,7,4,7,9,5,3,4,7
Explain
1. Obtain length 3 and number of arrays 2.
2. Walk through the first row to get 2,5,6;
3. Walk through the second line again to get 1,7,4;
4. Recycle back to the first line to get 7,9,5;
5. Walk through the second line again to get 3,4;
6. Go back to the first line and get 7, splicing into the final result in sequence.
Example 2
input
4
3
1,2,3,4,5,6
1,2,3
1,2,3,4
output
1,2,3,4,1,2,3,1,2,3,4,5,6
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { int len = Integer.parseInt(sc.nextLine()); int arrNum = Integer.parseInt(sc.nextLine()); String[][] strArr = new String[arrNum][]; int maxLen = 0; for (int i = 0; i < arrNum; i++){ String str = sc.nextLine(); if (str.length() > 0){ strArr[i] = str.split(","); if (strArr[i].length > maxLen){ maxLen = strArr[i].length; } } } int index = 0; StringBuilder sb = new StringBuilder(); while (index < maxLen){ for (int i = 0; i < arrNum; i++){ String[] arr = strArr[i]; if (arr == null){ continue; } for (int j = index; j < index + len; j++){ if (j < arr.length){ sb.append(arr[j]).append(","); } } } index += len; } int lastIndex = sb.lastIndexOf(","); if (lastIndex != -1){ sb.deleteCharAt(lastIndex); } System.out.println(sb); } } }
48. Array Reduplication and Sorting
Given an unordered array, delete all duplicate elements so that each element appears only once, sorted from highest to lowest, and the same occurrences are sorted in the first occurrence order.
Enter a description:
An array
Output description:
Desorted Array
Example 1
input
1,3,3,3,2,4,4,4,5
output
3,4,1,2,5
Remarks:
Array size does not exceed 100
Array element value size does not exceed 100
Answer:
Solution 1:
import java.util.Scanner; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import java.util.Set; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String line = sc.nextLine(); String[] numbers = line.split(","); int[] ints = new int[numbers.length]; for (int i = 0; i < ints.length; i++) { ints[i] = Integer.valueOf(numbers[i]); } LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>(); for (int i = 0; i < ints.length; i++) { if (map.isEmpty()) { map.put(ints[i], 1); } else { if (map.containsKey(ints[i])) { int value = map.get(ints[i]); value++; map.put(ints[i], value); } else { map.put(ints[i], 1); } } } Set<Map.Entry<Integer, Integer>> set = map.entrySet(); LinkedList<Map.Entry<Integer, Integer>> list = new LinkedList<>(set); list.sort((o1, o2) -> o2.getValue() - o1.getValue()); for (int i = 0; i < list.size(); i++) { Map.Entry<Integer, Integer> entry = list.get(i); if (i != list.size() - 1) { System.out.print(entry.getKey() + ","); } else { System.out.println(entry.getKey()); } } } }
49. Minimum number of arrays
Given an integer array, select three elements from the array to make up the minimum number and output (if the array length is less than 3, select all elements in the array to make up the minimum number).
Enter a description:
An integer array with a line of string records separated by a half-corner comma, 0 < array length <= 100, 0 < range of integers <= 10000.
Output description:
The smallest number of three elements. If the length of the array is less than 3, select all the elements in the array to make up the smallest number.
Example 1
input
21,30,62,5,31
output
21305
Explain
Array longer than 3, need to select 3 elements to make up the minimum number, 21305 consists of 21,30,5 elements, for the smallest number in all combinations
Example 2
input
5,21
output
215
Explain
Array length is less than 3, select all elements to the minimum of the main city, 215 to the minimum.
Answer:
Solution 1:
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class Main { public static void main(String[] args) { //Get input stored in array Scanner scanner = new Scanner(System.in); String inputString = scanner.nextLine(); String[] numberArr = inputString.split(","); //Calculation if(numberArr.length<=0){ return; }else if(numberArr.length ==1 ){ //Only one number, direct output System.out.println(numberArr[0]); }else if(numberArr.length ==2 ){ //There are two numbers, just put them together int s1 = Integer.parseInt(numberArr[0] + numberArr[1]); int s2 = Integer.parseInt(numberArr[1] + numberArr[0]); System.out.println(s1<s2?s1:s2); }else { //More than three numbers, sort first to find the smallest three in combination Arrays.sort(numberArr, new Comparator<String>() { @Override public int compare(String o1, String o2) { return Integer.parseInt(o1)-Integer.parseInt(o2); } }); String[] min3Num = Arrays.copyOf(numberArr,3); Arrays.sort(min3Num); String res=""; for (String s:min3Num){ res += s; } System.out.println(res); } } }
50. Number of daffodils
The so-called daffodil number refers to a positive n-bit integer whose n-th power of each digit is equal to the number itself. For example, 153 is the number of daffodils, 153 is a three-digit number, and 153 = 1^3 + 5^3 + 3^3.
Enter a description:
The first line enters an integer n, which represents a positive n-bit integer. N is between 3 and 7 and contains 3 and 7.
The second line enters a positive integer m to indicate that you need to return the mth daffodil.
Output description:
Returns the number of m daffodils whose length is n. Number starts at 0.
If m is greater than the number of daffodils, the product of the last number of daffodils and M is returned.
Return -1 if the input is not valid.
Example 1
input
3 0
output
153
Explain
153 is the first number of daffodils
Example 2
input
9
1
output
-1
Explain
9 out of range
Answer:
Solution 1:
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main{ public static void main(String[] args) { //Number of daffodils calcute1(); } public static void calcute1(){ Scanner sc = new Scanner(System.in); int n = sc.nextInt();//digit if (n >= 3 && n <= 7){ int m = sc.nextInt();//Number One int temp = 1; for (int i = 0 ; i < n ; i ++){ temp *= 10; } int min = temp / 10; int max = temp- 1; Map<Integer, Integer> data = new HashMap<>(); int count = 0; int lastNum = 0; for (int i = min ; i <= max ; i ++){ if (isRightNum(i, n)) { data.put(count++, i); if (i > lastNum){ lastNum = i; } } } if (data.containsKey(m)){ System.out.println(data.get(m)); } else { System.out.println(lastNum * m); } } else { System.out.println(-1); } } public static boolean isRightNum(int num, int n){ boolean result = false; String[] numStrs = String.valueOf(num).split(""); int[] data = new int[numStrs.length]; for (int i = 0 ; i < numStrs.length; i ++){ data[i] = Integer.parseUnsignedInt(numStrs[i]); } int sum = 0; for (int i = 0 ; i < n ; i ++){ sum += getCalcuteNum(data[i], n); } if (sum == num){ result = true; } return result; } public static int getCalcuteNum(int a, int b){ int result = 1; for (int i = 0; i < b ; i ++){ result *=a; } return result; } }
51. Product of prime numbers
RSA encryption algorithm is ubiquitous in the network security world. It takes advantage of the difficulty of maximum integer factor decomposition. The larger the data, the higher the security factor. Given a 32-bit positive integer, decompose it by factor to find out which product of two prime numbers is.
Enter a description:
A positive integer num
0 < num <= 2147483647
Output description:
If found successfully, split into single spaces, output two prime numbers from small to large, and decomposition fails, output -1-1
Example 1
input
15
output
3 5
Explain
After factoring, two prime numbers 3 and 5 are found, making 3*5 = 15. After sorting from smallest to largest, the output is 3.5
Example 2
input
27
output
-1 -1
Explain
By factoring, no prime numbers are found, so their product is 27, and the output is -1 -1
Answer:
Solution 1:
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); long num = sc.nextLong(); long limit = (long)Math.floor(Math.sqrt(num)); String res = ""; boolean flag = false; for(long i = 2;i<=limit;i++){ if(num%i==0){ if(isPrime(i)&&isPrime(num/i)){ flag = true; if(i<num/i){ res = i+" "+num/i; } else{ res = num/i+" "+i; } } } } if(flag==true){ System.out.println(res); } else{ System.out.println("-1 -1"); } } public static boolean isPrime(long num){ long limit = (long)Math.floor(Math.sqrt(num)); for(long i = 2;i<=limit;i++){ if(num%i==0) return false; } return true; } }
52. Maximum area of solar panels
To add a rectangular or square solar panel to one side of the spacecraft (the red diagonal area in the image), two pillars (the black vertical bar in the image) need to be installed before the solar panel is fixed in the middle of the pillar. However, the length of the support in different positions of the spacecraft varies, and the mounting area of the solar panels is limited by the length of the support on the shortest side. Figure:
A set of integer array pillar height data is provided. Assuming the distance between each pillar is equal to one unit length, how to select two pillars to maximize the area of the solar panel is calculated.
Enter a description:
10,9,8,7,6,5,4,3,2,1
Note: There are at least 2 pillars, up to 10,000, which can support integers in the height range of 1~10^9. The height of the column is out of order, and descending in the example is just a coincidence.
Output description:
Maximum solar panel area that can be supported: (between 10m high pillar and 5m high pillar)
25
Example 1
input
10,9,8,7,6,5,4,3,2,1
output
25
Remarks:
The width between the 10m high pillar and the 5m high pillar is 5, the smaller the height is 5, and the area is 25. The other two pillars would each yield less than 25 acres. So the maximum solar panel area is 25.
Answer:
Solution 1:
import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] strs = sc.nextLine().split(","); int len = strs.length; long res = 0; for(int i = 0; i < len - 1; i++) { for(int j = i + 1; j < len; j++) { long a = Long.valueOf(strs[i]); long b = Long.valueOf(strs[j]); long c = j - i; if (a > b){ if (res < b * c) res = b * c; }else{ if (res < a *c) res = a * c; } } } System.out.print(res); } }
53. Parking lot vehicle statistics
A parking lot of a certain size, with arrays cars[] denoting, where 1 denotes having a car and 0 denotes having no car. Vehicles vary in size, with cars occupying one parking space (length 1), trucks occupying two parking spaces (length 2), and trucks occupying three parking spaces (length 3). The minimum number of vehicles that can be parked in a parking lot is counted and the specific number is returned.
Enter a description:
An integer string array cars[], where 1 indicates a car, 0 indicates no car, and the array length is less than 1000.
Output description:
An integer numeric string that represents the minimum number of parks.
Example 1
input
1,0,1
output
2
Explain
1 car occupies the first parking space
The second parking space is empty
A car occupies the third parking space
There are at least two cars
Example 2
input
1,1,0,0,1,1,1,0,1
output
3
Explain
1 truck occupies 1st and 2nd parking spaces
Parking spaces 3 and 4 are empty
1 truck occupies 5th, 6th, 7th parking spaces
Eighth parking space is empty
One car occupies the 9th parking space
Minimum 3 vehicles
Answer:
Solution 1:
import java.util.*; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); while (scan.hasNext()) { String line = scan.next(); if(line.split(",").length >= 1000){ System.out.println(0); continue; } int result = 0; String[] split = line.replaceAll(",", "").split("0+"); if(split != null && split.length != 0){ for (int i = 0; i < split.length; i++){ String temp = split[i]; if(temp.length() == 1 || temp.length() == 2 || temp.length() == 3){ result ++; }else { int length = temp.length(); if(length % 3 == 0){ result = result + length / 3; }else { result = result + length / 3 + 1; } } } } System.out.println(result); } } }
54. Statistics of Shooting Competition Results
Given a score sheet of a shooting competition, which contains scores of several shootings by multiple players, rank each player in descending order by the sum of their highest three points. Output the ID sequence of the players in descending order. The conditions are as follows:
1. A player may have scores of multiple shooting results in an irregular order.
2. If a player has less than three results, all results of the player are considered invalid and the ranking ignores the player.
3. If the results of the players are equal, the players whose results are equal are listed in descending order according to their ID.
Enter a description:
Enter the first line, an integer N, to indicate that a total of N shots were made in the game, resulting in N score points (2<=N<=100).
Enter the second line, a sequence of N integers representing the player ID (0<=ID<=99) for each shoot.
Enter the third line, a sequence of N integers, representing the corresponding score of each shooter (0<=score<=100).
Output description:
The ID sequence of the descending ranked player that meets the criteria for setting a title.
Example 1
input
13
3,3,7,4,4,4,4,7,7,3,5,5,5
53,80,68,24,39,76,66,16,100,55,53,80,55
output
5,3,7,4
Explain
The shooting competition took place 13 times with {3,4,5,7} competitors.
Player 3 scored 53,80,55, and the sum of the highest three results was 80+55+53=188.
No. 4 player's results: 24,39,76,66, the sum of the highest three results is 76+66+39=181.
No. 5 player's results: 53,80,55, the sum of the highest three results: 80+55+53=188.
Player 7 scored 68,16,100, and the sum of the highest three results was 100+68+16=184.
Comparing the sum of the highest three results of each competitor, there are 3 = 5 > 7 > 4. Since the results of 3 and 5 are equal and ID number 5 > 3, the output is: 5,3,7,4
Answer:
Solution 1:
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String a = in.nextLine(); String b = in.nextLine(); String[] bSplit = b.split(","); String c = in.nextLine(); String[] cSplit = c.split(","); Map<Integer, Integer> countMap = new java.util.HashMap<>(); Map<Integer, Integer> cjMap = new java.util.HashMap<>(); Map<Integer, List<Integer>> cjDataMap = new java.util.HashMap<>(); for (int i = 0; i < Integer.valueOf(a); i++) { Integer mc = Integer.valueOf(bSplit[i]); Integer cj = Integer.valueOf(cSplit[i]); if (countMap.containsKey(mc)) { countMap.put(mc, countMap.get(mc) + 1); // cjMap.put(mc, cjMap.get(mc) + cj); List<Integer> data = cjDataMap.get(mc); insertList(data, cj); cjDataMap.put(mc, data); } else { List<Integer> data = new ArrayList<>(); insertList(data, cj); countMap.put(mc, 1); // cjMap.put(mc, cj); cjDataMap.put(mc, data); } } for (Entry<Integer, List<Integer>> data : cjDataMap.entrySet()) { if (data.getValue().size() < 3) { continue; } for (int i = 0; i < data.getValue().size(); i++) { if (i > 2) { break; } if (cjMap.containsKey(data.getKey())) { cjMap.put(data.getKey(), cjMap.get(data.getKey()) + data.getValue().get(i)); } else { cjMap.put(data.getKey(), data.getValue().get(i)); } } } Map<Integer, Integer> countMapOne = new java.util.HashMap<>(); Map<Integer, Integer> cjMapOne = new java.util.HashMap<>(); List<Integer> cjList = new ArrayList<>(); for (Entry<Integer, Integer> count : countMap.entrySet()) { if (count.getValue() >= 3) { countMapOne.put(count.getKey(), count.getValue()); cjMapOne.put(count.getKey(), cjMap.get(count.getKey())); if (!cjList.contains(cjMap.get(count.getKey()))) { insertList(cjList, cjMap.get(count.getKey())); } } } String ss = ""; for (Integer integer : cjList) { List<Integer> mcList = new ArrayList<>(); for (Entry<Integer, Integer> count : cjMapOne.entrySet()) { if (count.getValue().toString().equals(integer.toString())) { insertList(mcList, count.getKey()); } } for (Integer integer2 : mcList) { ss += integer2 + ","; } } System.out.println(ss.substring(0, ss.length() - 1)); } private static void insertList(List<Integer> cjList, Integer integer) { for (int i = 0; i < cjList.size(); i++) { if (cjList.get(i) < integer) { cjList.add(i, integer); break; } if (i == cjList.size() - 1) { cjList.add(integer); break; } if (cjList.get(i) > integer && cjList.get(i + 1) < integer) { cjList.add(i + 1, integer); break; } } if (cjList.isEmpty()) { cjList.add(integer); } } }
55. Post-order traversal of non-leaf parts of a complete binary tree
Given a complete binary tree sequence (up to 1000 integers) that stores complete values in a sequential storage structure, find out all non-leaf node parts of the complete binary tree, and then use a post-order traversal to output this part of the tree (excluding leaves).
1. A tree with only one node that is identified as the root node (not a leaf).
2. This complete binary tree is not a full binary tree. There may be leaves on the second last layer or no right leaves on it.
Other Notes: Post-order traversal of a binary tree is root-based, and the traversal order is left-right-root
Enter a description:
An integer sequence string split by spaces
Output description:
Non-leaf partial tree structure
Example 1
input
1 2 3 4 5 6 7
output
2 3 1
Explain
Find the non-leaf partial tree structure and use the subsequent traversal output
Remarks:
Output numbers separated by spaces
Answer:
Solution 1:
import java.util.*; /** * 1. Build Binary Tree * 2. Culling out leaf nodes * 3. Post-order traversal * <p> * 1 2 3 4 5 6 7 8 9 10 11 12 */ public class Main { static class Node { private int val; private Node left; private Node right; public Node() { } public Node(int val) { this.val = val; } public Node(int val, Node left, Node right) { this.val = val; this.left = left; this.right = right; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); String[] ss = in.nextLine().split(" "); for (String s : ss) { queue.add(Integer.parseInt(s)); } Node root = build(); remove(root); List<String> p = new ArrayList<>(); print(root, p); System.out.println(String.join(" ", p)); } private static Queue<Integer> queue = new ArrayDeque<>(); private static Queue<Node> nodes = new ArrayDeque<>(); public static Node build() { Node root = new Node(queue.poll()); nodes.add(root); while (!nodes.isEmpty()) { Node top = nodes.poll(); if (!queue.isEmpty()) { Node left = new Node(queue.poll()); top.left = left; nodes.add(left); } else { break; } if (!queue.isEmpty()) { Node right = new Node(queue.poll()); top.right = right; nodes.add(right); } else { break; } } return root; } public static Node remove(Node root) { if (root == null) { return null; } if (root.left == null && root.right == null) { return null; } root.left = remove(root.left); root.right = remove(root.right); return root; } public static void print(Node root, List<String> p) { if (root == null) { return; } print(root.left, p); print(root.right, p); p.add(String.valueOf(root.val)); } }
56. Master Player
Given an integer array of length n, it represents the face fraction a player can choose in an n-round. Players play cards based on rules. Calculate the highest total score they can get after all rounds. The selection rules are as follows:
1. In each round, if a player has the option to acquire the face, his total score plus the face score will be his new total score.
2. A player may also skip directly to the next round without choosing the face of the card. At this time, the current total score is restored to the total score before the third round. If the current round is less than or equal to 3 (that is, the first, second and third rounds are selected to skip), the total score is set to 0.
3. The player's initial total score is 0 and must participate in each round in turn.
Enter a description:
The first behavior is a string split by a lowercase comma, representing the face score of n rounds, 1<= n <=20.
The score value is an integer, -100 <=the score value <= 100.
No formatting considerations.
Output description:
The highest total score a player gets at the end of all rounds.
Example 1
input
1,-5,-6,4,3,6,-2
output
11
Explain
There are 7 rounds of cards in total.
The first round selects the face of the card with a total score of 1.
The second round does not select the face and the total score is restored to zero.
The third round does not select the face and the total score is restored to zero.
The fourth round selects the face of the card with a total score of 4.
The fifth round selects the face of the card with a total score of 7.
The sixth round selects the face, with a total score of 13.
If you do not select the face in the seventh round, the total score will be restored to the score before the third round 1, that is, the total score of the fourth round 4. If you choose the face, the total score will be 11, so choose the face.
Therefore, the final maximum total score is 11.
Answer:
Solution 1:
import java.util.*; public class Main { public static void main(String[] args) { testAdd(); } public static void testAdd(){ //1,-5,-6,4,3,6,-2 Scanner scan = new Scanner(System.in); while (scan.hasNext()) {// Note that if the input is multiple test cases, use the while loop to process multiple test cases String str = scan.nextLine(); if(str != null){ String[] split = str.split(","); int num = 0; int[] ints = new int[split.length]; for (int i = 0; i < split.length; i++) { int var = Integer.parseInt(split[i]); //Negative first three digits without adding if(i < 3){ num += var; if(num < 0){ num = 0; } }else{ //Determine whether to abstain int anInt = ints[i - 3];//The total score in the first three rounds is if(anInt > (num + var)){ num = anInt; }else{ num += var; } } ints[i] = num;//Record the total score for each round } if(ints.length > 0){ if(split.length >= 20){ System.out.println(ints[19]); }else { System.out.println(ints[split.length - 1]); } } } } } }
57. Relative Opening Syllables
Relatively open syllables are composed of consonants + vowels (aeiou) + consonants (except r) + e. Common words are bike, cake, and so on.
Given a string, invert the letters in each word with a space separator, without inversion if the word contains other non-letters, such as numbers.
After inversion, the number of substrings with relative open syllable structure is calculated (some characters in a continuous substring can be repeated).
Enter a description:
String, multiple words separated by spaces, string length <10000, letters only considered lowercase
Output description:
Number of substrings with relative open syllable structure, Note: Number < 10000
Example 1
input
ekam a ekac
output
2
Explain
Make a cache after inversion where make and cache are relative open syllable substrings, returning 2
Example 2
input
!ekam a ekekac
output
2
Explain
Reverse to! ekam a cakeke because! ekam contains non-English characters and is not inverted, where cake and keke are relative syllable substrings and return 2
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNextLine()) { String[] temp = sc.nextLine().split("\\s+"); System.out.println(handle(temp)); } sc.close(); } public static int getCount(String str) { if (str.length() < 4) { return 0; } int val = 0; if (!zimu(str)) { for (int i = 0; i <= str.length() - 4; i++) { if (check(str.charAt(i), str.charAt(i + 1), str.charAt(i + 2), str.charAt(i + 3))) { val++; } } } else { for (int i = str.length() - 1; i > 2; i--) { if (check(str.charAt(i), str.charAt(i - 1), str.charAt(i - 2), str.charAt(i - 3))) { val++; } } } return val; } public static boolean check(char c1, char c2, char c3, char c4) { if (c4 != 'e') { return false; } if (c2 != 'a' && c2 != 'e' && c2 != 'i' && c2 != 'o' && c2 != 'u') { return false; } if (c1 == 'a' || c1 == 'e' || c1 == 'i' || c1 == 'o' || c1 == 'u') { return false; } if (!('a' <= c1 && c1 <= 'z')) { return false; } if (c3 == 'a' || c3 == 'e' || c3 == 'i' || c3 == 'o' || c3 == 'u' || c3 == 'r') { return false; } if (!('a' <= c3 && c3 <= 'z')) { return false; } return true; } public static int handle(String[] temp) { int count = 0; for (int i = 0; i < temp.length; i++) { count += getCount(temp[i]); } return count; } public static boolean zimu(String s) { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (!('a' <= c && c <= 'z')) { return false; } } return true; } }
58. Fun games
Rule of the game: Enter a string containing only English letters. Two letters in the string can be eliminated if they are adjacent and identical.
The elimination action is repeated on the string until the elimination cannot continue, and the game is over.
Output the resulting string length.
Enter a description:
Enter the original string str, which can only contain uppercase and lowercase letters. The letters are case sensitive and the str length does not exceed 100.
Output description:
Output After Game Ends, Final String Length
Example 1
input
gg
output
0
Explain
gg can be directly eliminated, resulting in an empty string of length 0
Example 2
input
mMbccbc
output
3
Explain
In mMbccbc, cc can be eliminated first. The string becomes mMbbc and the bb can be eliminated. At this point the string becomes mMc and there are no adjacent and identical characters to continue eliminating. The resulting string is mMc with a length of 3
Remarks:
When the input contains non-uppercase letters, they are all abnormal inputs and return 0 directly
Answer:
Solution 1:
import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String a = in.nextLine(); char[] str = a.toCharArray(); Stack<Character> stack = new Stack<Character>(); boolean flag = true; for(int i=0;i<str.length;i++){ String sss = String.valueOf(str[i]).toLowerCase(); char ssss = sss.charAt(0); if((ssss < 'a' || ssss > 'z')){ System.out.println(0); flag = false; break; } if(stack.size()>0 && str[i] == stack.peek()){ stack.pop(); }else{ stack.push(str[i]); } } if(flag){ System.out.println(stack.size()); } } }
59. Find children of similar height
Xiao Ming went to the first grade of primary school this year. When he came to the new class, he found that other children were uneven in height. Then he wanted to sort them based on their height difference. Please help him achieve the sorting.
Enter a description:
The first behavior is positive integer H and N, 0 < H < 200, for smart height, 0 < N < 50, for the number of other children in the new class.
The second behavior had N positive integers H1-HN, which were the heights of other children, ranging from 0<Hi<200 (1<=i<=N), and N positive integers were different.
Output description:
Output sorting results, with positive integers divided by spaces. The children with the smallest absolute height difference and the children with the largest absolute height difference were in the first place, and the smaller children were in the first place if the two children had the same height difference.
Example 1
input
100 10
95 96 97 98 99 101 102 103 104 105
output
99 101 98 102 97 103 96 104 95 105
Explain
Small Ming Height 100, 10 students in the class, height is 95 96 97 98 99 101 102 103 104 105, sorted by height difference, the result is: 99 101 98 102 97 103 96 104 95 105.
Answer:
Solution 1:
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main{ public static void main(String [] args) throws Exception{ Scanner scan = new Scanner(System.in); while(scan.hasNextInt()){ int height = scan.nextInt(); int nums = scan.nextInt(); Map <Integer,Integer> map =new HashMap(); int max=0; for(int i=0;i<nums;i++){ int otherHeight = scan.nextInt(); int cha = otherHeight-height; max = Math.max(Math.abs(cha), max); map.put(cha, otherHeight); } for(int m=0;m <=max;m++){ if(m==0){ if(map.get(0)!=null) System.out.print(map.get(m)+" "); continue; } if(map.get(0-m)!=null){ System.out.print(map.get(0-m)+" "); } if(map.get(m)!=null){ System.out.print(map.get(m)+" "); } } } } }
60. Find the same substring
Give you two strings T and p, ask to find a continuous substring from t that is the same as p, and output the subscript of the first character of the string.
Enter a description:
The input file consists of two lines representing strings t and p, guaranteeing that the length of t is not less than p, and that the length of t is not more than 1000000, and that of P is not more than 10000.
Output description:
If a continuous substring equal to p is found from t, the subscript of the first character of the substring in t is output (from left to right is 1,2,3,...); If not, output "No"; If there are multiple such substrings, the output has the smallest subscript for the first character.
Example 1
input
AVERDXIVYERDIAN
RDXI
output
4
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String []args){ Scanner sc = new Scanner(System.in); String t = sc.nextLine(); String p = sc.nextLine(); int index = t.indexOf(p); if(index == -1){ System.out.println("No"); }else{ System.out.println(index + 1); } } }
61. Decompression of a compressed string representation
There is a simple compression algorithm: for strings that consist entirely of lower-case English letters, compress the parts that exceed two consecutive identical letters into consecutive numbers plus the letters, and leave the rest unchanged. For example, the string "aaabbccccd" is compressed to the string "3abb4cd". Please write an decompression function to determine if the string you entered is a legally compressed string. If the input is legitimate, the decompressed string will be output. Otherwise, the output string'!Error'will report an error.
Enter a description:
Enter a line for an ASCII string that will not exceed 100 characters in length and the use case guarantees that the output string will not exceed 100 characters in length
Output description:
If the input is judged to be a valid compressed string, the compressed string is output. If the input is not valid, the output string'!error'.
Example 1
input
4dff
output
ddddff
Explain
4d expands to dddddd, so the decompressed string is ddddddff
Example 2
input
2dff
output
!error
Explain
Two DS d o not require compression, so the input is illegal
Example 3
input
4d@A
output
!error
Explain
The special characters @ and capital letter A do not appear after compressing a string consisting of all lowercase English letters, so the input is illegal
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str, tmp, res; char ch; int count; while (scanner.hasNext()) { str = scanner.next(); res = ""; if (str.matches(".*[^0-9a-z].*") || str.matches("^.*[0-9]+$")) { System.out.println("!error"); continue; } for (int i = 0, k, len = str.length(); i < len; i++) { ch = str.charAt(i); tmp = ""; if (ch >= 'a' && ch <= 'z') { k = i; for (k = i + 1; k < len; ++k) { if (ch != str.charAt(k)) { break; } } if (k - i > 2) { res = "!error"; break; } } while (ch >= '0' && ch <= '9') { tmp += ch; ++i; ch = str.charAt(i); } if (!tmp.isEmpty()) { count = Integer.parseInt(tmp); if (count < 3) { res = "!error"; break; } for (int j = 0; j < count; j++) { res += ch; } } else { res += ch; } } System.out.println(res); } } }
62. English Input Method
Your supervisor expects you to achieve word association in IME. The requirements are as follows:
Based on the prefix of the word entered by the user, associate the words that the user wants to enter from the English sentences already entered. Output the associative word sequence in dictionary order. If not, output the prefix of the word entered by the user.
Be careful:
- Case sensitive when associating English words
- Abbreviations such as "don't" are defined as two words, "don" and "t"
- Output word sequence, no duplicate words, only English words, no punctuation
Enter a description:
The input is two lines.
Enter a sentence str consisting of the English word word word and punctuation in the first line.
Next, do a prefix pre for the English word.
0 < word.length() <= 20
0 < str.length <= 10000
0 < pre <= 20
Output description:
Output a required word sequence or word prefix, with multiple words separated by a single space
Example 1
input
I love you
He
output
He
Explain
Three words "I", "love", "you" are extracted from the user-entered English sentence "I love you". Then the user enters "He". No words that meet the requirements can be associated with the input information, so the prefix of the word entered by the user is output.
Example 2
input
The furthest distance in the world, Is not between life and death, But when I stand in front of you, Yet you don't know that I love you.
f
output
front furthest
Explain
The furthest distance in the world, Is not between life and death, But when I stand in front of you, Yet you dont know that I love you. The extracted words, prefixed with "f", are "furthest" and "front", sorted in dictionary order and output after adding spaces between words, resulting in "front furthest".
Answer:
Solution 1:
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextLine()) {// Note that if the input is multiple test cases, use the while loop to process multiple test cases String[] arr = in.nextLine().split("[^a-zA-Z]+"); String key = in.nextLine(); List<String> result = new ArrayList<>(); for (String str : arr) { if (str.startsWith(key) && !result.contains(str)) { result.add(str); } } if (result.isEmpty()) { System.out.println(key); } else { Collections.sort(result); StringBuffer tmp = new StringBuffer(); for (String str : result) { tmp.append(str).append(" "); } System.out.println(tmp.toString().trim()); } } } }
62. User Scheduling Problem
A common problem in communication systems is dispatching users with different strategies, which results in different system consumption and performance.
Assuming there are currently n schedulers to be serialized, each user can use three different scheduler strategies, A/B/C, which consume different system resources. Please schedule your users according to the following rules and return the total number of resources consumed.
Rules:
-
Neighboring users cannot use the same scheduling policy, for example, the first user uses A Policy, the second user can only use B perhaps C Strategy.
-
For a single user, the consumption of system resources by different scheduling strategies can be normalized and abstracted into numbers. For example, a user might use A/B/C System consumption for policy is 15/8/17.
-
Each user then chooses the one that consumes the least system resources (locally optimal) currently available, and if there are multiple strategies that meet the requirements, chooses the last one.
Enter a description:
The first line represents the number of users n
Next each line represents the system consumption resA resB resC for a user using three strategies
Output description:
Total System Resource Consumption under Optimal Policy Combination
Example 1
input
3
15 8 17
12 20 9
11 7 5
output
24
Explain
User 1 uses policy B, user 2 uses policy C, and user 3 uses policy B. System resource consumption: 8 + 9 + 7 = 24.
Remarks:
All policies consume a positive integer for system resources, n < 1000
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNextInt()) { int number = scanner.nextInt(); int[][] input = new int[number][3]; for (int i = 0; i < number; i++) { for (int j = 0; j < 3; j++) { input[i][j] = scanner.nextInt(); } } int preSelectedIndex = -1; long sum = 0; for (int i = 0; i < number; i++) { int min = 0; int currentMinIndex = 0; for (int j = 0; j < 3; j++) { if ((min == 0 && preSelectedIndex != j) || (input[i][j] <= min && preSelectedIndex != j)) { min = input[i][j]; currentMinIndex = j; } } preSelectedIndex = currentMinIndex; sum += min; } System.out.println(sum); } } }
63. Express integers by the sum of consecutive natural numbers
An integer can be represented by the sum of consecutive natural numbers. Given an integer, the expression that calculates the sum of several consecutive natural numbers is printed out.
Enter a description:
A target integer T (1 <=T<= 1000)
Output description:
The number of all expressions and expressions of the integer. If there are multiple expressions, the output requirement is:
1. Expressions with the least number of natural numbers output first
2. Each expression is output in increasing order of natural numbers. See example for specific format. At the end of each test data, a line "Result:X" is output, where X is the final number of expressions.
Example 1
input
9
output
9=9
9=4+5
9=2+3+4
Result:3
Explain
Integer 9 has three representations, the first expression has only one natural number, the first one outputs, the second expression has two natural numbers, the second order outputs, the third expression has three natural numbers, and the last output. The natural numbers in each expression are output in increasing order.
No spaces between numbers and symbols
Example 2
input
10
output
10=10
10=1+2+3+4
Result:2
Answer:
Solution 1:
import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { int taget = scanner.nextInt(); findAllResult(taget); } // findAllResult(10); } private static void findAllResult(int t){ //Store results Stack<String> res = new Stack<>(); int count = 0; //Expression ending in i for (int i = 1; i <=t; i++) { int tempR=t; int p = i; StringBuilder sb = new StringBuilder(); sb.append(t).append("="); while (p<=t && tempR>0) { tempR-=p; sb.append(p).append(tempR==0 ? "" : "+"); p++; } if (tempR==0) { count++; res.push(sb.toString()); } } while (!res.isEmpty()) { System.out.println(res.pop()); } System.out.println("Result:"+count); } }
64. Location
There is a row of parking spaces in the parking lot. 0 means no parking and 1 means a car. At least one car was parked in the parking space and at least one empty space was not parked.
To prevent obstruction, a parking space needs to be found for the parker, so that the nearest vehicle to the parker's car is the maximum distance, and the maximum distance back at that time is returned.
Enter a description:
1. A parking identification string separated by a half-corner comma. The parking identification is either 0 or 1, 0 is empty, and 1 is parked.
2. The maximum number of parking spaces is 100.
Output description:
Output an integer to record the maximum distance.
Example 1
input
1,0,0,0,0,1,0,0,1,0,1
output
2
Explain
When parked in the third position, the nearest distance to the car is 2 (1 to 3).
When parked in the fourth position, the nearest distance to the car is 2 (4 to 6).
Other location distances are 1.
So the maximum distance is 2.
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String line = sc.next(); String[] place = line.split(","); int count = 0, max = 0, left = 0; for (String s : place) { if (s.equals("0")) { count++; } else { if (left == 0) { max = count * 2; left = 1; } else { max = Math.max(max, count); } count = 0; } } if (place[place.length - 1].equals("0")) { max = Math.max(max, count * 2); } else { max = Math.max(max, count); } System.out.println((max + 1) / 2); } }
65. Find a string substring that meets the requirements
Given two strings, find all the characters in string 1 from string 2, de-duplicate them and sort them from smallest to largest ASCII values
Input string 1: Length not exceeding 1024
Input string 2: no longer than 1000000
Character range meets ASCII encoding requirements, sorted from small to large ASCII values
Enter a description:
bach
bbaaccedfg
Output description:
abc
Example 1
input
fach
bbaaccedfg
output
acf
Explain
Remarks:
Input string 1 is given as bach, input string 2 bbaaccedfg
Find the character of string 1 from string 2, remove duplicate characters, and sort ASCII values from small to large. The output is abc.
The character h in string 1 cannot be found in string 2 without output.
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s =new Scanner(System.in); String str1=s.nextLine(); String str2=s.nextLine(); char[] arr2=str2.toCharArray(); int[] arr4=new int[150]; for(char c:arr2){ if(str1.contains(c+"")){ int b=(int)c; arr4[(int)c]=1; } } for(int i=1;i<arr4.length;i++){ if(arr4[i]==1){ System.out.print((char)i); } } } }
66. Find Friends
In school, N little friends stand in a line, and the ith little friend is tall [i],
The first kid j that the ith kid can see is taller than himself, so j is a good friend of I I (ask j > i).
Please regenerate a list. The output of the corresponding location is the location of each friend's good friend. If you do not see a good friend, replace it with 0.
The number of children ranges from [0,40,000].
Enter a description:
Enter N in the first line, N means you have N children
The second line enters the height[i] of N little friends, which are all integers
Output description:
Output the location of friends of N little friends
Example 1
input
2
100 95
output
0 0
Explain
The first child is 100 tall, standing at the end of the queue and looking at the first one. There is no taller child than him, so the first output value is 0.
The second child stood at the head of the team, and there was no taller child in front of him, so the second value was 0.
Example 2
input
8
123 124 125 121 119 122 126 123
output
1 2 6 5 5 6 0 0
Explain
123's best friend is 124 in 1 place
124 Friends are 125 in 2 places
125's Friend is 126 in 6
And so on
Answer:
Solution 1:
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[][] map = new int[n][m]; int maxNum = 0; int num[] = new int[n]; for(int i = 0 ; i < n ; i ++){ for(int j = 0; j < m ; j ++){ map[i][j] =sc.nextInt(); } } for(int i =0 ;i <n;i++){ int[] hang = new int[m]; int[] lie = new int[m]; for(int j = i;j < n ; j ++){ for(int k = 0;k<m;k++){ hang[k] = hang[k]+map[j][k]; maxNum =Math.max(maxNum,hang[k]); lie[0] =hang[0]; for(int s=1;s<m;s++){ if(lie[s-1]<0){ lie[s] = hang[s]; }else{ lie[s] =lie[s-1]+hang[s]; } maxNum = Math.max(maxNum,lie[s]); } } } } System.out.println(maxNum); } }
67. Find End Point
Given a positive integer array, set to nums, with a maximum of 100 members, start with the first member and go exactly to the last member of the array, using the minimum number of steps.
Requirement:
1. The first step must start with the first element and 1<=the step of the first step<len/2; (len is the length of the array and needs to be resolved by itself).
2. From the second step, you can only take the corresponding number of steps with the number of members you belong to, not more or less. If the target is not reachable and returns to -1, only the minimum number of steps will be output.
3. You can only go to the end of the array, not back.
Enter a description:
An array of positive integers, separated by spaces, with an array length less than 100. Resolve the number of data yourself.
Output description:
A positive integer representing the minimum number of steps, if no output-1 exists
Example 1
input
7 5 9 4 2 6 8 3 5 4 3 9
output
2
Explain
First step: Choose 2 for the first optional step, starting from the first member 7 and going 2 steps to 9; Step 2: From 9 onwards, go through 9 members corresponding to their own number 9 to the end.
Example 2
input
1 2 3 7 1 5 9 3 2 1
output
-1
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String line = scanner.nextLine(); String[] eles = line.split(" "); int [] datas = new int[eles.length]; for (int index = 0; index < eles.length; index++) { datas[index] = Integer.parseInt(eles[index]); } findPath(datas); } } private static void findPath(int[] datas) { int minStep = -1; int current = 0; for (int firstStep = 1; firstStep < datas.length / 2; firstStep++) { current = firstStep; int step = 1; while (current < datas.length - 1) { current += datas[current]; step++; } if (current == datas.length - 1) { if (minStep == -1) minStep = step; else if (minStep > step) minStep = step; } } System.out.println(minStep); } }
68. Integer Encoding
Implements an integer encoding method so that the smaller the number to be encoded, the smaller the number of bytes used after encoding.
The coding rules are as follows:
1. When encoding, a set of 7 bits, the lower 7 bits of each byte are used to store the complement of the number to be encoded.
2. The highest bit of a byte indicates whether there are subsequent bytes, 1 indicates more bytes, and 0 indicates that the current byte is the last byte.
3. Use small end-order encoding with low bits and bytes on the low address.
3. The result of encoding is output in the character format of hexadecimal digits, and the lowercase letters need to be converted to uppercase letters.
Enter a description:
The input is a non-negative integer represented by a string
Output description:
Output a string representing an integer-encoded hexadecimal stream
Example 1
input
0
output
00
Explain
Output of 16-digit characters, less than two before 0, such as 00, 01, 02.
Example 2
input
100
output
64
Explain
The binary representation of 100 is 0110 0100, requiring only one byte to encode.
The highest position of the byte is 0, and the remaining 7 bits store the lower 7 bits of the number 100 (110,0100), so the encoded output is 64.
Example 3
input
1000
output
E807
Explain
The binary representation of 1000 is 0011 1110 1000 and requires at least two bytes to encode.
The highest position of the first byte is 1, and the remaining 7 bits store the first low 7 bits (110,000) of the number 1000, so the binary of the first byte is 110,000, or E8;
The second byte has the highest position of 0, and the remaining 7 bits store the second low 7 bits (000 0111) of the number 1000, so the binary of the first byte is 0000 0111, or 07;
Small end-order encoding is used, so low-byte E8 output comes first and high-byte 07 output comes last.
Remarks:
The range of numbers to be encoded is [0, 1 < 64 - 1]
Answer:
Solution 1:
import java.io.IOException; import java.util.Scanner; public class Main { public static void main(String[] args) throws InterruptedException, IOException { Scanner in = new Scanner(System.in); long l = in.nextLong(); //To Binary String s = Long.toBinaryString(l); //If less than 7 bits, add 0 before StringBuilder sb = new StringBuilder(7); if (s.length() % 7 != 0) for (int i = 0; i < 7 - s.length() % 7; i++) { sb.append("0"); } s = sb.toString() + s; //Output hexadecimal in specified order getRes(s); } private static void getRes(String s) { int index = s.length(); StringBuilder res = new StringBuilder(); while (index > 7) { int num = Integer.parseInt("1" + s.substring(index - 7, index), 2); String hex = Integer.toHexString(num); if (hex.length() == 1) { res.append(1); } res.append(hex); index -= 7; } //Parse Last int num = Integer.parseInt("0" + s.substring(0, 7), 2); String hex = Integer.toHexString(num); if (hex.length() == 1) { res.append(0); } res.append(hex); System.out.println(res.toString().toUpperCase()); } }
69. Minimum sum of integer pairs
Given two integer array1, array2, the array elements are sorted in ascending order. Assuming that an element from array1 and array2 can form a pair of elements, it is now necessary to take out k pairs of elements, sum all the elements and calculate the minimum of the sum.
Note: Two pairs of elements are considered the same if they correspond to both subscripts in array1 and array2.
Enter a description:
Enter two rows of array1, array2, the first number of each row is the size of the array (0 < size <= 100);
0 < array1[i] <= 1000
0 < array2[i] <= 1000
Next behavior is positive integer k
0 < k <= array1.size() * array2.size()
Output description:
Minimum sum that meets the requirements
Example 1
input
3 1 1 2
3 1 2 3
2
output
4
Explain
In the use case, you need to take two pairs of elements
Take the 0th element of the first array and the 0th element of the second array to form a pair of elements [1,1];
Take the first element of the first array and the tenth element of the second array to form a pair of elements [1,1];
The sum is 1+1+1+1+1=4, the minimum sum required
70. Array of integers sorted by bit values
Given a non-empty array (list) with an integer element data type, sort the lowest decimal bit of the array element from smallest to largest, and keep the relative position of the elements with the same lowest decimal bit.
When an array element is negative, the lowest decimal bit is the same as the lowest decimal bit when the symbol bit is removed.
Enter a description:
Given a non-empty array with element data type of 32-bit signed integer and array length [1,1000]
Output description:
Output sorted array
Example 1
input
1,2,5,-21,22,11,55,-101,42,8,7,32
output
1,-21,11,-101,2,22,42,32,5,55,7,8
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); String [] strs = str.split(","); StringBuffer sb= new StringBuffer(); int i = 0; while(i<=9) { for(String s : strs) { int a = Integer.parseInt(s.substring(s.length()-1)); if(a == i) { sb.append(s).append(","); } } i++; } String str2 = sb.toString(); str2 = str2.substring(0,str2.length()-1); System.out.print(str2); } }
71. Execution Duration
In order to make full use of the GPU's computing power, you need to hand over as many tasks as possible to the GPU. There is now an array of tasks whose elements represent the number of new tasks added in this second and each second has new tasks. Assuming that the GPU performs at most n tasks at a time, one second at a time, and at least how long it takes the GPU to complete without idling.
Enter a description:
The first parameter is the maximum number of tasks performed by the GPU at a time, in the range [1,10000]
The second parameter is the length of the task array, in the range [1,10000]
The third parameter is the task array, the number range [1,10000]
Output description:
Minimum number of seconds to complete all tasks
Example 1
input
3
5
1 2 3 4 5
output
6
Explain
Perform up to three tasks at a time, with a minimum time of 6s
Example 2
input
4
5
5 4 1 1 1
output
5
Explain
Up to four tasks at a time, with a minimum time of 5s
Answer:
Solution 1:
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); while (s.hasNextInt()) { int max = s.nextInt(); int count = s.nextInt(); List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < count; i++) { list.add(s.nextInt()); } compute(list, max); } s.close(); } static void compute (List<Integer> list, int max) { int sum = 0; int time = list.size(); for (int i = 0; i < list.size(); i++) { sum += list.get(i); if (sum >= max) { sum = sum - max; } else { sum = 0; } } if (sum == 0) { System.out.println(time); } else { if (sum%max == 0) { time += sum/max; System.out.println(time); } else { time += (sum/max + 1); System.out.println(time); } } } }
72. String Transform Minimum String
Given a string s, a transformation can only take place at most once, returning the smallest string that can be obtained after the transformation (compared in dictionary order).
Transform rule: swap any two characters in a string at different positions.
Enter a description:
A string of lowercase letters s
Output description:
Minimum string to be transformed as required
Example 1
input
abcdef
output
abcdef
Explain
abcdef is already the smallest string, no exchange is required
Example 2
input
bcdefa
output
acdefb
Explain
a and b exchange positions until the smallest string
Remarks:
s is composed of all lowercase characters
1<=s.length<=1000
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String str = scan.next(); if (str == null || str.isEmpty()) { return; } char[] charArray = str.toCharArray(); int minIndex = 0; int minCharValue = Integer.valueOf(charArray[0]); for (int i = 0; i < charArray.length; i++) { int charValue = Integer.valueOf(charArray[i]); if (charValue <= minCharValue) { minCharValue = charValue; minIndex = i; } } if (minIndex == 0) { System.out.println(str); } else { char temp = charArray[0]; charArray[0] = charArray[minIndex]; charArray[minIndex] = temp; System.out.println(String.valueOf(charArray)); } } }
73. String Split
Given a non-empty string S, which is separated by N'-'into N+1 substrings and a positive integer K, the remaining substrings, with the exception of the first substring, are required to form a new substring with each K character separated by'-'. For each new substring, if it contains more lowercase letters than uppercase letters, all uppercase letters of the substring are converted to lowercase letters. Conversely, if it contains more upper-case letters than lower-case letters, all lower-case letters of this substring are converted to upper-case letters. Do not convert when the number of upper and lower case letters is equal.
Enter a description:
The input is two lines, the first behavior parameter K and the second behavior string S.
Output description:
Output converted string.
Example 1
input
3
12abc-abCABc-4aB@
output
12abc-abc-ABC-4aB-@
Explain
Substring 1212bc, abCABc, 4aB@, the first substring is reserved, followed by a substring of 3 characters each group for abC, ABc, 4aB, @, abC has more lowercase letters, converts to abc, ABc has more uppercase letters, converts to ABC, 4aB has 1 uppercase letter, does not convert, @ has no letters, that is, 12abc-abc-ABC-4aB-@
Example 2
input
12
12abc-abCABc-4aB@
output
12abc-abCABc4aB@
Explain
The substring is 1212bc, abCABc, 4aB@, the first one is reserved, and the next one is abCABc4aB@ every 12 characters. There are 4 uppercase and lowercase letters in this substring. Without conversion, it is 12abc-abCABc4aB@
Answer:
Solution 1:
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextInt()) { int k = in.nextInt(); String s = in.next(); char[] chars = s.toCharArray(); int indexOfOne = s.indexOf("-"); List<String> resList = new ArrayList<>(); resList.add(s.substring(0, indexOfOne)); StringBuilder tmp = new StringBuilder(); int up = 0; int low = 0; int length = 0; for (int i = indexOfOne; i < chars.length; i++) { char c = chars[i]; if ('A' <= c && c <= 'Z') { up += 1; tmp.append(c); length += 1; } else if ('a' <= c && c <= 'z'){ low += 1; tmp.append(c); length += 1; } else if (c != '-') { tmp.append(c); length += 1; } if (length == k || chars.length -1 == i) { String str = tmp.toString(); if (up > low) { resList.add(str.toUpperCase()); } else if (up < low) { resList.add(str.toLowerCase()); } else { resList.add(str); } tmp.delete(0,length); up = 0; low = 0; length = 0; } } System.out.println(String.join("-",resList)); } } }
74. String Encryption
Give you a string of unencrypted strings str, encrypted by changing each letter of the string by offsetting a specific array element a[i] from each letter str[i], the first three of which have been assigned a[0]=1,a[1]=2,a[2]=4. When i>=3, the array element a[i]=a[i-1]+a[i-2]+a[i-3],
For example, the original abcde encrypted bdgkr with offsets of 1,2,4,7,13.
Enter a description:
The first behavior is an integer n (1<=n<=1000), which means there are N sets of test data, each set of data contains one row, the original str (only contains lowercase letters, 0<length<=50).
Output description:
Output one line per set of test data representing the ciphertext of the string
Example 1
input
1
xy
output
ya
Explain
The first character x offset is 1, that is, y, and the second character y offset is 2, that is, a
Example 2
input
2
xy
abcde
output
ya
bdgkr
Explain
The second line output character offsets are 1, 2, 4, 7, 13, respectively
Remarks:
Answer Requirements
Time limit: 2000ms, memory limit: 64MB
75. String Filter Sort
Enter a string consisting of n uppercase and lowercase letters. Look for the letter of the kth smallest ASCII code value in the string (k>=1) in the order of the Ascii code values from smallest to largest, and output the position index of the string in which the letter is located (the first character position index of the string is 0).
k If greater than the string length, the position index of the string where the letter of the maximum ascii value is output, and the minimum position index of the output letter if there are duplicate letters.
Enter a description:
The first line enters a string of upper and lower case letters
The second line input k, K must be greater than 0, K can be greater than the length of the input string
Output description:
The position index of the string in which the letter of the kth smallest ascii code value in the output string is located. k If greater than the string length, the position index of the string in which the letter of the maximum ascii value is output, and the minimum position index of the letter of the kth minimum ascii code value is output if there are duplicates.
Example 1
input
AbCdeFG
3
output
5
Explain
Sorted by ascii code value, the third smallest ascii code value has the letter F and the position index of F in the string is 5 (0 is the position index of the first letter of the string)
Example 2
input
fAdDAkBbBq
4
output
6
Explain
Sorted by ascii code value, the first four letters are AABB, because B is duplicated, only B's (first) smallest position index 6 is taken, not B's position index 8
Answer:
Solution 1:
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner in = new Scanner(System.in); while (in.hasNext()){ String item = in.nextLine(); int k = Integer.parseInt(in.nextLine()); char[] arrs = item.toCharArray(); Arrays.sort(arrs); if(k>arrs.length){ char max = arrs[arrs.length-1]; System.out.println(item.indexOf(max)); }else{ char max = arrs[k-1]; System.out.println(item.indexOf(max)); } } } }
76. String Statistics
Given two character sets, one is the full character set and the other is the occupied character set. Characters in the occupied character set can no longer be used, requiring the output of the remaining available character sets.
Enter a description:
1. The input is a string that must contain the @ symbol. The first is the full character set, and the second @ is the occupied character set.
2. Characters in the occupied character set must be those in the full character set. Characters in the character set are separated by English commas.
3. Each character is represented as a character plus a number, separated by an English colon, such as a:1, which represents a character.
4. Characters are case-sensitive and letters are only considered. Numbers are only considered for orthographic shaping and the number does not exceed 100.
5. If none of the characters are occupied, @ identifiers still exist, such as a:3,b:5,c:2@
Output description:
Output available character sets, carriage return line breaks between different output character sets.
Note that the output is in the same character order as the input. Cannot output b:3,a:2,c:2
If a character is completely occupied, no further output is required.
Example 1
input
a:3,b:5,c:2@a:1,b:2
output
a:2,b:3,c:2
Explain
The full character set is 3 a, 5 b, 2 c.
The occupied character set is one a, two b.
Since the occupied characters can no longer be used, the remaining available characters are 2 a, 3 b, and 2 c.
So output a:2,b:3,c:2
Answer:
Solution 1:
import java.util.LinkedHashMap; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) {// Note that if the input is multiple test cases, use the while loop to process multiple test cases String a = in.nextLine(); String[] s = a.split("@"); String[] pre = s[0].split(","); if(s.length >1) { LinkedHashMap<String, Integer> map = new LinkedHashMap(); for (String temp : pre) { String[] temp2 = temp.split(":"); map.putIfAbsent(temp2[0], (Integer) map.getOrDefault(temp2[0], 0) + Integer.valueOf(temp2[1])); } String[] end = s[1].split(","); for (String temp : end) { String[] temp2 = temp.split(":"); map.put(temp2[0], map.get(temp2[0]) - Integer.valueOf(temp2[1])); } StringBuilder stringBuilder = new StringBuilder(); map.entrySet().forEach(f-> { Map.Entry entry = ( Map.Entry)f; if(f.getValue()>0) { stringBuilder.append(entry.getKey()+":"+ entry.getValue()); stringBuilder.append(","); } }); if(stringBuilder.length()>0) stringBuilder.delete(stringBuilder.lastIndexOf(","),stringBuilder.length()); System.out.println(stringBuilder.toString()); } else { System.out.println(s[0]); } } } }
77. String Sequence Decision
Enter two strings, S and L, containing only lowercase letters. S length<=100, L length<=500,000. Determines whether S is a valid string for L.
Decision rule: every character in S can be found in L (can be discontinuous), and the order of the characters in L should be the same as that in S. (For example, S="a C e" is a subsequence of L="abcde" and the valid characters are a, c, e, whereas "a e c" is not a valid subsequence and the valid characters are only a, e)
Enter a description:
Enter two strings, S and L, containing only lowercase letters. S length<=100, L length<=500,000.
Enter S first, then L, one line for each string.
Output description:
The position of the last valid character of the S string in L. (The first calculation starts at 0 and returns -1 without a valid character)
Example 1
input
ace
abcde
output
4
Example 2
input
fgh
abcde
output
-1
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scin = new Scanner(System.in); while(scin.hasNextLine()){ String S=scin.nextLine(); String L=scin.nextLine(); System.out.println(loIndex(S,L)); } } private static int loIndex(String S,String L){ int lastIndex=-1; for (int i=0;i<S.length();i++){ boolean isFind=false; for(int j=lastIndex+1;j<L.length();j++){ if(S.charAt(i)==L.charAt(j)){ // Update coordinates lastIndex=j; isFind=true; break; } } if(!isFind){ return lastIndex; } } return lastIndex; } }
78. Character Statistics and Rearrangement
Gives a string containing only letters, no spaces, counts the number of occurrences of each letter (case sensitive) in the string, and outputs each letter and its occurrences in the order of number of occurrences, from large to small. If the number of times is the same, sort in natural order, with lowercase letters before uppercase letters.
Enter a description:
Enter a line for a string containing only letters.
Output description:
Output each letter and number of letters in the order of the number of occurrences of letters, separated by English semicolons, paying attention to the semicolons at the end; The letters and times are separated by English colons.
Example 1
input
xyxyXX
output
x:2;y:2;X:2;
Explain
The number of occurrences of each character is 2, so x precedes y and the lowercase letter X precedes X
Example 2
input
abababb
output
b:4;a:3;
Explain
b occurs more than a, so b comes before a
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); int[] a = new int[256]; for (int i = 0; i < str.length(); i ++) { a[str.charAt(i)] ++; } int max = 0; for (int i : a) { max = Math.max(i ,max); } for (int i = max; i > 0; i --) { for (int j = 97; j < 123; j ++) { if (a[j] == i) { System.out.print((char)j); System.out.print(":"); System.out.print(i); System.out.print(";"); } } for (int j = 65; j < 91; j ++) { if (a[j] == i) { System.out.print((char)j); System.out.print(":"); System.out.print(i); System.out.print(";"); } } } } }
79. Max Composition
Each member of the group has a card, which is a positive integer in six digits. By linking the cards together, you can make up many numbers and calculate the maximum number.
Enter a description:
Multiple positive integer strings separated by a sign, without considering non-numeric exceptions, up to 25 people in the group
Output description:
Maximum number string
Example 1
input
22,221
output
22221
Example 2
input
4589,101,41425,9999
output
9999458941425101
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); String[] s = str.split(","); String sum = ""; for (int i = 0; i < s.length-1; i++) { for (int j = i+1; j < s.length ; j++) { String s1 = s[i].length() >= s[j].length() ? s[i] : s[j]; String s2 = s[i].length() < s[j].length() ? s[i] : s[j]; for (int k = 0; k < s2.length(); k++) { if ((k == s2.length() - 1) && (s1.charAt(k) == s2.charAt(k))) { if (k == s1.length() - 1) { break; } else if ((s1.charAt(k + 1) < s2.charAt(0))) { String s3 = s1; s1 = s2; s2 = s3; break; } } else { if (s1.charAt(k) < s2.charAt(k)) { String s3 = s1; s1 = s2; s2 = s3; break; }else if (s1.charAt(k) > s2.charAt(k)) { break; } } } s[i]=s1; s[j]=s2; } } for (int i = 0; i <s.length ; i++) { sum+=s[i]; } System.out.println(sum); } }
80. The sum of the maximum and minimum N
Given an array, write a function to calculate the sum of its maximum and minimum N numbers. You need to weight the array.
Explain:
*Number range in array [0,1000]
*Maximum N and Minimum N cannot overlap. If overlap occurs, the input returns -1 illegally
*Input Illegal Return-1
Enter a description:
The first line inputs M, which identifies the size of the array
The second line enters M numbers to identify the contents of the array
The third line input N, N expression needs to calculate the maximum and minimum N number
Output description:
Sum of the minimum and maximum N outputs.
Example 1
input
5
95 88 83 64 100
2
output
342
Explain
Maximum 2 [100,95], Minimum 2 [83,64], Output 342
Example 2
input
5
3 2 3 4 2
2
output
-1
Explain
Max 2 [4,3], min 2 [3,2], with overlapping output of -1
Answer:
Solution 1:
import java.util.Scanner; import java.util.TreeSet; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int size = scanner.nextInt(); if (size < 2) { System.out.println(-1); return; } int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = scanner.nextInt(); } int length = scanner.nextInt(); if (length < 0 || length > size / 2) { System.out.println(-1); return; } // sort TreeSet<Integer> set = new TreeSet<>(); for (int i = 0; i < size; i++) { set.add(array[i]); } int newSize = set.size(); if (length > newSize / 2) { System.out.println(-1); return; } Object[] newArray = set.toArray(); int result = 0; for (int i = 0; i < length; i++) { result += (int) newArray[i] + (int) newArray[newSize - 1 - i]; } System.out.println(result); } }
81. Maximum Expense Amount
Xiao Ming wants to buy some of the items he likes because of the discount on many of the items he sells. However, he decided to buy three of the items he likes due to the limitation of purchase funds. He also wants to spend as much money as possible. Now, please design a program to help Xiao Ming calculate the maximum amount of money he can spend.
Enter a description:
Enter a one-dimensional integer array M of the first behavior, the length of the array is less than 100, the elements of the array record the price of a single commodity, and the price of a single commodity is less than 1000.
Enter the amount R of the second act purchase fund, which is less than 100000.
Output description:
The output is the maximum amount of money spent to satisfy the above conditions.
Note: If there is no product that meets the above criteria, please return to -1.
Example 1
input
23,26,36,27
78
output
76
Explain
Amounts 23, 26 and 27 add up to 76 and are closest and less than the input amount 78
Example 2
input
23,30,40
26
output
-1
Explain
Because of the imported goods, it is not possible to combine them to satisfy the sum of three items less than 26. So return to -1
Remarks:
The input format is correct, regardless of the format error.
Answer:
Solution 1:
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] arr = sc.next().split(","); String sum = sc.next(); int[] arri = new int[arr.length]; for (int i = 0; i <arr.length; i++) { arri[i] = Integer.parseInt(arr[i]); } System.out.println(find(arri,arr.length,Integer.parseInt(sum))); } public static int find(int a[],int size,int sum) { List<Integer> result = new ArrayList<>(); int left,right; //Sort Arrays First Arrays.sort(a); //For a tuple, first fix an element, looking for a sum-val for(int i=0;i<size-2;i++)//i is a subscript to a fixed value { left=i+1;//When the whole on the right side of I is solved as a left binary, the left ft starts with the first one, which is the position of i+1 right=size-1;//Rightis the last value, nothing to do with the end of i, going directly to the last element, size-1 while(left<right) { if(a[i]+a[left]+a[right]<=sum) { // return a[i]+a[left]+a[right]; result.add(a[i]+a[left]+a[right]); left++; } else { right--; } } } Collections.sort(result); return result.get(result.size()-1); } }
82. Maximum matrix sum
Given a two-dimensional integer matrix, to select a sub-matrix in this matrix so that all the numbers in the sub-matrix are as large as possible, we call this sub-matrix and the maximum sub-matrix. The selection principle of the sub-matrix is a rectangular area which is continuous with each other in the original matrix.
Enter a description:
The first row of input contains two integers n, m (1 <= n, m <= 10), representing a matrix of N rows and m columns. There are n rows below, each row has m integers. In the same row, there is one space between each two numbers, and there is no space after the last number. All numbers are between [-1000, 1000].
Output description:
Output a row of numbers representing the sum of all the numbers in the selected and largest submatrices.
Example 1
input
3 4
-3 5 -1 5
2 4 -2 4
-1 3 -1 3
output
20
Explain
In a 3*4 matrix, the sum of the submatrices of the last 3 columns equals 20, and the maximum.
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main (String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String[] str = sc.nextLine().split(" "); int n = Integer.parseInt(str[0]); int m = Integer.parseInt(str[1]); int[][] map = new int[n][m]; long result = Long.MIN_VALUE; for (int i = 0; i < n; i++) { String[] item = sc.nextLine().split(" "); for (int j = 0; j < m; j++) { map[i][j] = Integer.parseInt(item[j]); } } for (int start = 0; start < n; start++) { long[] ring = new long[m]; long[] dp = new long[m]; for (int end = start; end < n; end++) { for (int j = 0; j < m; j++) { ring[j] += map[end][j]; } result = Math.max(result, ring[0]); dp[0] = ring[0]; for (int j = 1; j < m; j++) { if (dp[j - 1] < 0) { dp[j] = ring[j]; } else { dp[j] = dp[j - 1] + ring[j]; } result = Math.max(result, dp[j]); } } } System.out.println(result); } } }
83. Maximum bracket depth
The existing string consists of only six brackets'(',')','{','}','[',']'.
A string is invalid if it meets one of the following conditions:
(1) The number of left and right parentheses of any type is not equal;
(2) There are brackets that are not closed in the correct order (left then right).
The maximum nesting depth of output brackets, or 0 if the string is invalid.
0 < String Length < 100000
Enter a description:
A string containing only'(',')','{','}','[',']'
Output description:
An integer, maximum bracket depth
Example 1
input
[]
output
1
Explain
Valid string, maximum nesting depth 1
Example 2
input
([]{()})
output
3
Explain
Valid string, maximum nesting depth 3
Example 3
input
(]
output
0
Explain
Invalid string, there are two types of unequal number of left and right parentheses
Example 4
input
([)]
output
0
Explain
Invalid string, there are parentheses not closed in the correct order
Example 5
input
)(
output
0
Explain
Invalid string, there are parentheses not closed in the correct order
Answer:
Solution 1:
import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String inputStr = scanner.nextLine(); char[] chars = inputStr.toCharArray(); int len = chars.length; if (len % 2 != 0) { System.out.println("0"); return; } int maxDepth = 0; int signLeftMin = 0; // ( int signRightMin = 0; // ) int signLeftMiddle = 0; // [ int signRightMiddle = 0; // ] int signLeftMax = 0; // { int signRightMax = 0; // } for (int i = 0; i < len; i++) { if (signRightMin > signLeftMin || signRightMiddle > signLeftMiddle || signRightMax > signLeftMax) { maxDepth = 0; break; } if (chars[i] == '(') { signLeftMin++; } else if (chars[i] == ')') { signRightMin++; } else if (chars[i] == '[') { signLeftMiddle++; } else if (chars[i] == ']') { signRightMiddle++; } else if (chars[i] == '{') { signLeftMax++; } else if (chars[i] == '}') { signRightMax++; } } if (signRightMin != signLeftMin || signRightMiddle != signLeftMiddle || signRightMax != signLeftMax) { maxDepth = 0; } else { // Judging by Stack Stack<Character> stack = new Stack<>(); for (int i = 0; i < len; i++) { if (chars[i] == ')' || chars[i] == ']' || chars[i] == '}') { stack.pop(); int tempSize = stack.size(); if (tempSize > maxDepth) { maxDepth = tempSize; } } else { stack.push(chars[i]); int tempSize = stack.size(); if (tempSize > maxDepth) { maxDepth = tempSize; } } } } System.out.print(maxDepth); } }
84. Hiking trail
An expedition was responsible for exploring underground caves. When members of an expedition are on an expedition, the recorder they carry with them records their coordinates from time to time, but other data is also recorded in the gaps between the recordings. After the exploration, the expedition team needs to get the farthest footprint of a member relative to the expedition headquarters during the expedition.
- When the instrument records coordinates, the data format of coordinates is (x,y), such as (1,2), (100,200), where 0 < x < 1000, 0 < y < 1000. Illegal coordinates such as (01,1), (1,01), (0,100) are also present.
- Set the coordinates of the expedition headquarters to (0,0) and the distance of a location from the headquarters to: xx+yy.
- If both coordinates are the same distance from the headquarters, the first coordinate reached is the farthest footprint.
- If the coordinates in the recorder are not valid, output the headquarters coordinates (0,0).
Note: Nested double-brackets, such as sfsdfsd((1,2)), do not need to be considered.
Enter a description:
String representing the data in the recorder.
For example: ferga13fdsf3(100,200)f2r3rfasf(300,400)
Output description:
String representing the coordinates reached by the farthest hike.
For example: (300,400)
Example 1
input
ferg(3,10)a13fdsf3(3,4)f2r3rfasf(5,10)
output
(5,10)
Explain
There are three legitimate coordinates in the recorder: (3,10), (3,4), (5,10), where (5,10) is the farthest coordinate from the headquarters, and the output (5,10).
Example 2
input
asfefaweawfaw(0,1)fe
output
(0,0)
Explain
Coordinates in recorder are not valid, output headquarters coordinates (0,0)
Answer:
Solution 1:
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { String str = sc.nextLine(); int maxDistance = -1; String result = ""; while (true) { if (str.length() == 0) { break; } int leftIndex = str.indexOf("("); int rightIndex = str.indexOf(")"); if (leftIndex == -1 || rightIndex == -1) { break; } String ele = str.substring(leftIndex + 1, rightIndex); String[] es = ele.split(","); boolean flag = true; for (String s : es) { if (s.startsWith("0")) { flag = false; break; } if (Integer.parseInt(s) <= 0 || Integer.parseInt(s) >= 1000){ flag = false; break; } } if (flag == false) { str = str.substring(rightIndex + 1); continue; } int number1 = Integer.parseInt(es[0]); int number2 = Integer.parseInt(es[1]); int distance = number1 * number1 + number2 * number2; if (distance > maxDistance) { result = "(" + es[0] + "," + es[1] + ")"; maxDistance = distance; } str = str.substring(rightIndex + 1); } if (maxDistance == -1) { System.out.println("(0,0)"); } else { System.out.println(result); } } } }
85. Longest Continuous Subsequence
A sequence of N positive integers. Given the integer sum, find the longest sequential subsequence so that their sum equals the sum, return the length of this subsequence, and return -1 if no sequence meets the requirements.
Enter a description:
Sequence: 1,2,3,4,2
sum: 6
Output description:
Sequence length: 3
Enter a description:
Sequence: 1,2,3,4,2
sum: 6
Output description:
Sequence length: 3
Example 1
input
1,2,3,4,2
6
output
3
Explain
Interpretation: Both sequences 1,2,3 and 4,2 satisfy the requirements, so the longest continuous sequence is 1,2,3, so the result is 3
Example 2
input
1,2,3,4,2
20
output
-1
Explain
Interpretation: No subsequence meets the requirements, returning -1
Remarks:
The input sequence consists only of numbers and English commas, separated by English commas.
Sequence length: 1 <= N <= 200;
The input sequence does not take exception into account, and the title ensures that the input sequence meets the requirements.
Answer:
Solution 1:
import java.util.*; import java.io.*; public class Main{ public static void main(String[] rds)throws IOException{ Scanner br = new Scanner(System.in); String str = br.nextLine(); int sum = br.nextInt(); String[] list = str.split(","); int max = -1; for(int i =0;i<list.length;i++){ int temp = sum; for(int j = i;j<list.length;j++){ temp -= Integer.parseInt(list[j]); if(temp == 0){ max = max>j-i?max:j-i; } } } max = max >-1?max+1:-1; System.out.println(max); } }
86. Length of longest vowel substring
Definition: When a string consists of only vowel letters (aeiouAEIOU), it is called a vowel string.
Now given a string, find the longest vowel string and return its length. If not found, 0 is returned.
Substring: A subsequence of any consecutive character in a string is called a substring of that string.
Enter a description:
A string whose length range is 0 < length <= 65535.
Strings consist of only the characters A-Z and A-Z.
Output description:
An integer representing the length of the longest vowel string.
Example 1
input
asdbuiodevauufgh
output
3
Explain
Example 1 explains that the longest vowel substring is "uio" or "auu", and its length is 3, so output 3
Answer:
Solution 1:
import java.util.*; public class Main { public static void main(String[] args) { String source = "aeiouAEIOU"; Scanner sc = new Scanner(System.in); String str = sc.next(); int result = 0; int count = 0; for (int i = 0; i < str.length(); i++) { String temp = String.valueOf(str.charAt(i)); if(source.contains(temp)) { count++; } else { count = 0; } if(count > result) { result = count; } } System.out.println(result); } }
87. Length of the longest substring (1)
Give you the string s, which is connected to a ring at the beginning and end. Find out in the ring that the'o'character has the length of the longest substring even times.
Enter a description:
The input is a string of lowercase letters
Output description:
The output is an integer
Example 1
input
alolobo
output
6
Explain
One of the longest substrings is "alolob", which contains'o'2.
Example 2
input
looxdolx
output
7
Explain
The longest substring is "oxdolxl". Since the end and end are joined together, the last'x'and the beginning'l' are joined together. This string contains two'o'.
Example 3
input
bcbcbc
output
6
Explain
In this example, the string "bcbcbc" is itself the longest because'o'occurs zero times.
Remarks:
1 <= s.length <= 5 x 10^5
s contains only lowercase English letters.
Answer:
Solution 1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while(in.hasNext()) { String str = in.next(); int sum = 0; for(int i = 0; i < str.length(); i++) { char c = str.charAt(i); if(c == 'o') { sum += 1; } } int length = 0; if(sum % 2 == 0) { // if(str.charAt(0) == 'o') { length = str.length(); // } else { // length = str.length() + 1; // } } else { // if(str.charAt(0) == 'o') { // length = str.length() + 1; // } else { length = str.length() - 1; // } } System.out.println(length + ""); } } }