当前位置:网站首页>Interview related high-frequency algorithm test site 3
Interview related high-frequency algorithm test site 3
2022-07-05 04:06:00 【Xiao Zhang who came to study】
Catalog
One 、 All possible permutations of strings
Niuke link
describe :
Enter a string , Print out all the permutations of the characters in the string in dictionary order . For example, input string abc, Then print out by character a,b,c All the strings that can be arranged abc,acb,bac,bca,cab and cba .
import java.util.ArrayList;
import java.util.*;
public class Solution {
// Exchange characters
public void Swap(char[] str,int i,int j){
char tmp = str[i];
str[i] = str[j];
str[j] = tmp;
}
// Judge res Whether the string exists in
public boolean isExist(ArrayList<String> res,char[] str){
//String.valueOf(str) Convert an array of characters to a string
return res.contains(String.valueOf(str));
}
public void PermutationHelp(char[] str,int start,ArrayList<String> res){
if(start == str.length - 1){
// duplicate removal
if(!isExist(res,str)){
res.add(new String(str));
}
return;
}
for(int i = start;i < str.length;i++){
//start and i The relationship is : Indicates who to start with
// The first time is a and a swapping (a For the start element ), The second time is a and b swapping (b It becomes the starting element )
Swap(str,start,i);
// When determining which character to start with , It's about deciding the sort of arrangement of another part
//i Just decide who to start the arrangement with , But please sub The string starts each time , All from start+1 Start
// For example a As the starting element , Here we need to put bc Sort
// For example b For a start , Here we need to put ac Sort
PermutationHelp(str,start + 1,res);
// Switch to the original position again (abc)
Swap(str,start,i);
}
}
public ArrayList<String> Permutation(String str) {
ArrayList<String> res = new ArrayList<>();
if(str != null || str.length() > 0){
// Convert string to character array
PermutationHelp(str.toCharArray(),0,res);
// Print in dictionary order
Collections.sort(res);
}
return res;
}
}
Two 、TopK problem , The smallest output k Number
Niuke link
describe :
Given a length of n An array of possible duplicate values , Find the smallest one without weight removal k Number . For example, an array element is 4,5,1,6,2,7,3,8 this 8 A digital , The smallest 4 The number is 1,2,3,4( In any order ).
import java.util.ArrayList;
import java.util.*;
import java.util.Collections;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> list = new ArrayList<>();
if(input == null || k <= 0 || k > input.length){
return list;
}
PriorityQueue<Integer> queue = new PriorityQueue<>(k,Collections.reverseOrder());
for(int i = 0; i< input.length;i++){
if(i < k){
queue.offer(input[i]);
}else if(input[i] < queue.peek()){
queue.poll();
queue.offer(input[i]);
}
}
for(int i = 0;i < k;i++){
list.add(queue.poll());
}
return list;
}
}
3、 ... and 、 The maximum sum of successive subarrays
Niuke link
describe :
Enter a length of n Integer array array, One or more consecutive integers in an array form a subarray , The minimum length of the subarray is 1. Find the maximum sum of all subarrays .
Method 1 : have access to ( Dynamic gauge )dp complete
Define the State f(i): With i The sum of the largest continuous subsequences at the end of the subscript ;
State recurrence :f(i) = max(f(i-1)+array[i], array[i]) ;【 Be sure to pay attention to continuous keywords here 】
State initialization :f(0) = array[0], max = array[0];
public class Solution {
public int FindGreatestSumOfSubArray(int[] array) {
// if(array == null || array.length < 0){
// return -1;
// }
int[] dp = new int[array.length];
dp[0] = array[0];
int max = array[0];
for(int i = 1;i < array.length;i++){
dp[i] = Math.max(dp[i - 1] + array[i],array[i]);
if(max < dp[i]){
max = dp[i];
}
}
return max;
}
}
Method 2 : Improvement of the above dynamic gauge method
public class Solution {
public int FindGreatestSumOfSubArray(int[] array) {
int total= array[0];
int max = array[0];
// Used to detect i Sum of consecutive subsequences at the end of subscript
for(int i = 1;i < array.length;i++){
if(total > 0){
// If before total Cumulative sum >=0, Explain the current data +total, Conducive to the overall increase
total += array[i];
}else{
/// If the sum accumulated before <0, Explain the current data +total, It is not conducive to the overall increase , Discard all previous values
// Here is a basic fact , That is, the previous continuous data and are certain .
// continuity , It can be from the past to the present , It can also be from now to the future . As for whether to add it before , It seems that in the past, there was no contribution to the overall increase
total = array[i];
}
if(max < total){
max = total;
}
}
return max;
}
}
Four 、 Palindrome index
Niuke link
describe :
Given a string consisting only of lowercase letters . Now please find a location , After deleting that letter , The string becomes a palindrome . Please rest assured that there will always be a legal solution . If the given string is already a palindrome string , Then output -1.
Input description :
The first line contains T, Number of groups of test data . Followed by T That's ok , Each line contains a string .
Output description :
If you can delete a letter and make it a palindrome string , Then output the position of any deleted letter that meets the conditions ( Subscript from 0 Start ). for example :bcc, We can delete the position 0 Of b character .
Their thinking :
Statistics can be made from both sides , If different , Then delete any one , Then determine whether it is palindrome , If it is , Subscript is the subscript for deleting data , If not , Is the subscript of another element .
import java.util.Scanner;
public class Main{
public static boolean IsPalindrome(StringBuffer sb,int[] start,int[] end){
int i = 0;
int j = sb.length() - 1;
boolean flg = true;
while(i <= j){
if(sb.charAt(i) != sb.charAt(j)){
flg = false;
break;
}
i++;
j--;
}
if(start != null) start[0] = i;
if(end != null) end[0] = j;
return flg;
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
while(num > 0){
StringBuffer sb = new StringBuffer(scanner.next());
// Define subscripts in different positions of characters in the front and back arrays
int[] start = new int[1];
int[] end = new int[1];
// If it is palindrome index , The output -1
if(IsPalindrome(sb,start,end)){
System.out.println(-1);
}else{
// If it's not palindrome index , Then delete the next character ,
// Judge again
sb.deleteCharAt(end[0]);
if(IsPalindrome(sb,null,null)){
// If it's a palindrome string , Then the subscript of the character in this position is returned
System.out.println(end[0]);
}else{
// If the above judgment is not palindrome string , Is to delete the previous character subscript to get the palindrome string
// Because there is always a legal solution , Not delete the previous , Delete the following
System.out.println(start[0]);
}
}
num--;
}
}
}
5、 ... and 、 Make the array the smallest number
Niuke link
describe :
Enter an array of nonnegative integers numbers, Put all the numbers in the array together to form a number , Print the smallest of all the numbers that can be spliced .
For example, input array [3,32,321], Then print out the minimum number that these three numbers can be arranged into 321323.
1. The output can be very large , So you need to return a string instead of an integer ;
2. The stitched numbers may have a lead 0, The final result does not need to remove the lead 0;
For this question , The valid sequence we want is : Any element in the sequence y, And any element in front of it x Make an orderly combination to form xy, Than any element behind it z Carry out effective sequence combination yz, Meet the conditions xy < yz( Sort by dictionary sequence ).
import java.util.ArrayList;
import java.util.*;
public class Solution {
public String PrintMinNumber(int [] numbers) {
if(numbers == null){
return new String();
}
ArrayList<Integer> list = new ArrayList<>();
// Traverse each number in the array and add it to list Collection
for(int number : numbers){
list.add(number);
}
// Sort the elements in the set, splice characters, and compare the size
Collections.sort(list,new Comparator<Integer>(){
public int compare(Integer x,Integer y){
String A = x + "" + y;
String B = y + "" + x;
// Compare AB Size
return A.compareTo(B);
}
});
String res = new String();
for(Integer r : list){
res += r;
}
return res;
}
}
6、 ... and 、 The first common node of two linked lists
Niuke link
describe :
Enter two acyclic one-way linked lists , Find their first common node , If there is no public node, null is returned .( Note that because the incoming data is a linked list , So the error test data prompt is displayed in other ways , Make sure the incoming data is correct )
Their thinking : First, calculate the length of the two linked lists , Then let the long linked list take the difference step of the two linked lists first , Let the two linked lists go together , Until they meet their first public node .
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode headA = pHead1;
ListNode headB = pHead2;
int len1 = 0;
int len2 = 0;
while(headA != null){
len1++;
headA = headA.next;
}
headA = pHead1;
while(headB != null){
len2++;
headB = headB.next;
}
headB = pHead2;
int len = Math.abs(len1 - len2);
if(len1 > len2){
while(len > 0){
headA = headA.next;
len--;
}
}
else{
while(len > 0){
headB = headB.next;
len--;
}
}
while(headA != null && headB != null){
if(headB == headA){
return headA;
}
headA = headA.next;
headB = headB.next;
}
return null;
}
}
above .
边栏推荐
- 一文带你了解BI的前世今身与企业数字化转型的关系
- Threejs clicks the scene object to obtain object information, and threejs uses raycaster to pick up object information
- Is there a sudden failure on the line? How to make emergency diagnosis, troubleshooting and recovery
- Uni app common functions /api
- WGS84 coordinate system, web Mercator, gcj02 coordinate system, bd09 coordinate system - brief introduction to common coordinate systems
- A應用喚醒B應該快速方法
- Threejs loads the city obj model, loads the character gltf model, and tweetjs realizes the movement of characters according to the planned route
- Threejs realizes the drawing of the earth, geographical location annotation, longitude and latitude conversion of world coordinates threejs coordinates
- 为什么百度、阿里这些大厂宁愿花25K招聘应届生,也不愿涨薪5K留住老员工?
- 【看完就懂系列】一文6000字教你从0到1实现接口自动化
猜你喜欢

Clickhouse materialized view

输入的查询SQL语句,是如何执行的?

北京程序员的真实一天!!!!!

Threejs realizes sky box, panoramic scene, ground grass

官宣!第三届云原生编程挑战赛正式启动!

laravel8 导出Excle文件
![[wp][introduction] brush weak type questions](/img/d0/9eb3ade701057837d98e4a20082a10.png)
[wp][introduction] brush weak type questions

EasyCVR平台出现WebRTC协议视频播放不了是什么原因?

Looking back on 2021, looking forward to 2022 | a year between CSDN and me

Threejs factory model 3DMAX model obj+mtl format, source file download
随机推荐
技术教程:如何利用EasyDSS将直播流推到七牛云?
PlasticSCM 企业版Crack
[wp][introduction] brush weak type questions
UI自动化测试从此告别手动下载浏览器驱动
How is the entered query SQL statement executed?
Special Edition: spreadjs v15.1 vs spreadjs v15.0
Basic function learning 02
Deflocculant aminoiodotide eye drops
As soon as I write the code, President Wang talks with me about the pattern all day
Use of vscode software
Plasticscm enterprise crack
Ctfshow 2022 Spring Festival welcome (detailed commentary)
Wechat applet development process (with mind map)
NEW:Devart dotConnect ADO. NET
C语言课设:影院售票管理系统
为什么百度、阿里这些大厂宁愿花25K招聘应届生,也不愿涨薪5K留住老员工?
C language course setting: cinema ticket selling management system
Use Firefox browser to quickly pick up Web image materials
A application wakes up B should be a fast method
[Chongqing Guangdong education] 2408t Chinese contemporary literature reference test in autumn 2018 of the National Open University