第一题:
模拟。 初始位置在0,0 输入WASD W:向前走一格 S:原地 A:左转90 D:右转90
最后输出位置。
输入:WWW
输出:0 3
public class first {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
int x=0,y=0;
int c=0,d=0;//0,北,1,东,2,南,3,西
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='S') c++;
else if (s.charAt(i)=='W') {
if(d==0) y++;
else if(d==1) x++;
else if(d==2) y--;
else x--;
} else if (s.charAt(i)=='A') {
d=(d+3)%4;
}else {
d=(d+1)%4;
}
}
System.out.println(x+" "+y);
}
}
第二题:
n个数字,第i个+第j个=目标数字。 求结果
输入:3 4
2 2 2
输出:9
package jingdong;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* @Author dinghuapeng
* @Date 2024/8/10 19:40
* @PackageName:jingdong
* @ClassName: second
* @Description: TODO
* @Version 1.0
*/
public class second {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int x=sc.nextInt();
int[] a=new int[n];
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
map.put(a[i],map.getOrDefault(a[i],0)+1);
}
long res=count(a,map,x);
System.out.println(res);
}
public static long count(int[] arr,Map<Integer,Integer>map,int target){
long c=0;
for(int num:arr){
int com=target-num;
if(map.containsKey(com)){
c+=map.get(com);
}
}
return c;
}
}
哈希表秒了,需要注意答案的数量会超出int
第三题:
有一个数组,初始都是0
给一个目标数组,让初始数组变为目标数组。
每次可以选择一个区间,让里面的数字+1,或者*2
问最少需要多少次
输入:1 2 3 4 5
输出:4
输入:1 3 1 3 2
输出:5
思路:
贪心。先计算每一个位置上的数到目标数所需要的次数。然后计算总次数。 计算总次数的时候,如果这个次数比前一个次数小,不计算(因为在一个区间里,前一个就能使这个到达目标),如果这次比前一个大,则加上这次减前一个的次数。
public class thrid {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while (t-- > 0){
int n=sc.nextInt();
int[] b=new int[n];
for(int i=0;i<n;i++){
b[i]=sc.nextInt();
}
System.out.println(Min(b));
}
}
public static int Min(int[] b){
int[] c=new int[b.length];
int i=0;
for(int value:b){
while(value>1){
c[i]++;
if(value%2==1) c[i]++;
value/=2;
}
c[i]++;
i++;
}
int total=c[0];
for(i=1;i<c.length;i++){
if(c[i]>c[i-1]) total+=c[i]-c[i-1];
}
return total;
}
}