Day32 List
程序员文章站
2022-07-12 23:08:40
...
- 用 List 存储一些字符串,去除里面重复的字符串,只保留一个。
public class Test2List {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
String[] strings = {"xjn", "wmz", "chq", "wmz", "wsm", "lyh", "yzg", "wmz"};
for (String string : strings) {
if (!list.contains(string)) {
list.add(string);
}
}
System.out.println(list);
}
}
- 生成20个 1-20 的随机整数,把其中不重复的整数存入 List 集合中(相同的整数只存一个)。
public class Test3List {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 20; i++) {
Random random = new Random();
int value = random.nextInt(20) + 1;
if (!list.contains(value)) {
list.add(value);
}
}
System.out.println(list);
}
}
假设某个程序会进行一系列入栈和出栈的混合栈操作。入栈操作会将整数 0 到 9 按顺序压入栈;
出栈操作会打印除返回值。下面哪些序列是不可能产生的?
a. 4 3 2 1 0 9 8 7 6 5
b. 4 6 8 7 5 3 2 9 0 1
c. 2 5 6 7 4 8 9 3 1 0
d. 4 3 2 1 0 5 6 7 8 9
e. 1 2 3 4 5 6 9 8 7 0
f. 0 4 6 5 3 8 1 7 2 9
g. 1 4 7 9 8 6 5 3 0 2
h. 2 1 4 3 6 5 8 7 9 0
//(网上的代码,原本有部分不适用,已修改)
public class Test4 {
public static void main(String[] args) {
int[] a = {4, 3, 2, 1, 0, 9, 8, 7, 6, 5};
int[] b = {4, 6, 8, 7, 5, 3, 2, 9, 0, 1};
int[] c = {2, 5, 6, 7, 4, 8, 9, 3, 1, 0};
int[] d = {4, 3, 2, 1, 0, 5, 6, 7, 8, 9};
int[] e = {1, 2, 3, 4, 5, 6, 9, 8, 7, 0};
int[] f = {0, 4, 6, 5, 3, 8, 1, 7, 2, 9};
int[] g = {1, 4, 7, 9, 8, 6, 5, 3, 0, 2};
int[] h = {2, 1, 4, 3, 6, 5, 8, 7, 9, 0};
int[][] ints = new int[8][];
ints[0] = a;
ints[1] = b;
ints[2] = c;
ints[3] = d;
ints[4] = e;
ints[5] = f;
ints[6] = g;
ints[7] = h;
for (int[] anInt : ints) {
System.out.println(Arrays.toString(anInt));
System.out.println(isTrue(anInt));
}
}
public static boolean isTrue(int[] arr) {
boolean[] marked = new boolean[arr.length];
for (int i = 0; i < arr.length; i++) {
if (marked[i]) {
continue;
}
int cut = arr[i];
marked[i] = true;
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
if (arr[j] > cut) {
return false;
} else {
cut = arr[j];
}
marked[j] = true;
}
}
}
return true;
}
}
上一篇: 【LeetCode18】【双指针】每日一题day32
下一篇: Spring Aop:注解开发