Java语法day1
- 一、选择题
- 二、编程题
一、选择题
1、派生类调用基类的构造器必须用到的关键字(C)
A: this B: final C: super D: static
说明:调用父类的构造器或者父类的方法,要用关键字super
2、以下哪个接口的定义是正确的( D)
A: interface B{ void print() { } ;}
B: interface B{ static void print() ;}
C: abstract interface B extends A1, A2{ abstract void print(){ };} //A1、A2为已定义的接口
D: interface B{ void print();}
3、关键字super的作用是(D )
A: 用来访问父类被隐藏的非私有成员变量
B: 用来调用父类中被重写的方法
C: 用来调用父类的构造函数
D: 以上都是
4、将下列(A、B、C、D)哪个代码替换下列程序中的【代码】不会导致编译错误(A )
interface Com{
int M=200;
int f();
}
class ImpCom implements Com{
//【代码】
}
A: public int f(){ return 100+M;}
B: float f(){ return 100;}
C: public double f(){ return 2.6;}
D: public abstract int f()
5、默认类型等价表示是哪一项(C )
public interface IService {String NAME=“default”;}
A: public String NAME=“default”;
B: public static String NAME=“default”;
C: public static final String NAME=“default”;
D: private String NAME=“default”;
二、编程题
1、给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。解集 不能
包含重复的子集。你可以按 任意顺序 返回解集。 OJ链接 【LeetCode题号:78.子集】【中等】
public List<List<Integer>> subsets(int[] nums) {
int n = nums.length;//数组的长度
//构建集合 保存子集
List<List<Integer>> res = new ArrayList<>();
//遍历0/1序列的数,即0到(2^n-1),这里2^n即1<<n
for (int i = 0; i < (1 << n); i++) {
//每个0/1序列的数,即一个子集。所以构造一个集合来保存子集
List<Integer> sub = new ArrayList<>();
//取0/1序列的数,二进制的每一位j,即0到数组长度的位数
for (int j = 0; j < n; j++) {
//取每一位数,即(i>>j)&1,如果结果为1,则数组索引为j的元素,存在子集中
if ((((i >> j)) & 1) == 1) {
sub.add(nums[j]);
}
}
res.add(sub);
}
return res;
}
2、给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。你可以按 任何顺序 返回答案。 OJ链接【LeetCode题号:77. 组合】【中等】
//定义一个保存最终组合的集合,也是返回值
List<List<Integer>> result = new ArrayList<>();
//构造一个保存每个组合的集合,也是获取到k个元素的组合
Deque<Integer> sub = new ArrayDeque<>();
public List<List<Integer>> combine(int n, int k) {
//遍历开始,遍历时需要使用当前数字cur到n,且判断sub组合的长度为k时,
// 保存到result中。对于这里取全部组合,从1开始
dfs(n, k, 1);
return result;
}
private void dfs(int n, int k, int cur) {
// 递归终止条件是:sub 的长度等于 k
if (sub.size() == k) {
result.add(new ArrayList<>(sub));
return;
}
// 遍历可能的搜索起点
for (int i = cur; i <= n; i++) {
// 向保存组合的集合sub中添加当前数
sub.addLast(i);
// 求取包含当前数字 cur 时,子问题 cur+1 到 n 的组合
dfs(n, k, i + 1);
// 以上递归是深度优先遍历,获取的组合都是包含数字 cur 的,需要做相同的逆向操作,即回溯:删除 cur
sub.removeLast();
// 继续遍历,即为求取不包含 cur 的组合
}
}