1.题目: 排序子序列
排序子序列https://www.nowcoder.com/questionTerminal/2d3f6ddd82da445d804c95db22dcc471?orderBy HotValue=1&page=1&onlyReference=false
【题目解析】:
本题要求解的是排序子序列,排序子序列为非递增或者非递减,很多同学在这个非递增、非递减问题上很纠结,注意:非递减就是a[i]<=a[i+1],递减就是a[i]>a[i+1],非递增就是a[i]>=a[i+1],递增就是a[i]<a[i+1]。
import java.util.Scanner;
/**
* Created with IntelliJ IDEA.
* Description:排序子序列
* User: YAO
* Date: 2023-05-09
* Time: 16:00
*/
public class work2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int[] array = new int[a+1];
for (int i = 0; i < a; i++) {
array[i] = scanner.nextInt();
}
int i = 0;
int count = 0;
while (i < a){
if (array[i] >array[i+1]){
while (i < a && array[i] > array[i+1]){
i++;
}
i++;
count++;
}else if (array[i] == array[i+1]){
i++;
}else {
while (i < a && array[i] < array[i+1]){
i++;
}
i++;
count++;
}
}
System.out.println(count);
}
}
2. 题目: 倒置字符串
倒置字符串https://www.nowcoder.com/practice/ee5de2e7c45a46a090c1ced2fdc62355?tpId=85&&tqId=29867&rp =1&ru=/activity/oj&qru=/ta/2017test/question-ranking解题思路:
先将整个字符串逆置过来,再遍历字符串,找出每个单词,对单词逆置。
import java.util.*;
/**
* Created with IntelliJ IDEA.
* Description:将一句话的单词进行倒置,标点不倒置。比如 I like beijing. 经过函数后变为:beijing. like I
* User: YAO
* Date: 2023-05-09
* Time: 15:07
*/
public class work1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
char[] ch = str.toCharArray();
int len = ch.length;
//逆置整个字符串
reverse(ch,0,len-1);
//逆置每个单独的单词
int i = 0;
while (i < len){
int j = i;
while (j < len && ch[j] != ' '){
j++;
}
if (j < len){
reverse(ch,i ,j-1);
i = j + 1;
}else {
//此时逆置单词已经到了最后一个
reverse(ch, i, j-1);
i = j;
}
}
// 将字符数组准转换为字符串
String s = new String(ch);
System.out.println(s);
}
public static void reverse(char[] arr, int start, int end){
while (start <end){
char tmp = arr[start];
arr[start] = arr[end];
arr[end] = tmp;
start++;
end--;
}
}
}