选择题:
联合索引的查询语句、完全二叉数给出节点数求树的深度和叶子节点的个数。
笔试题
1. 合并两个有序链表 LeetCode21: 合并两个有序链表 https://leetcode-cn.com/problems/merge-two-sorted-lists/submissions/
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
package LeetCode;
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class DT143 {
public static void main(String[] args) {
ListNode node1 = new ListNode(0);
ListNode head1 = node1;
ListNode test = node1;
for(int i = 1; i < 25; i ++) {
node1.next = new ListNode(i);
node1 = node1.next;
}
while(test != null) {
System.out.print(test.val + " ");
test = test.next;
}
System.out.println("\n=================================\n");
ListNode node2 = new ListNode(1);
ListNode head2 = node2;
ListNode test1 = node2;
for(int i = 3; i < 15; i +=2) {
node2.next = new ListNode(i);
node2 = node2.next;
}
while(test1 != null) {
System.out.print(test1.val + " ");
test1 = test1.next;
}
System.out.println("\n=================================\n");
DT143 main = new DT143();
ListNode res = main.mergeTwoLists(head1,head2);
while(res != null) {
System.out.print(res.val + " ");
res = res.next;
}
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null) return l2;
if(l2 == null) return l1;
ListNode res = null;
if(l1.val > l2.val) {
res = new ListNode(l2.val);
l2 = l2.next;
} else {
res = new ListNode(l1.val);
l1 = l1.next;
}
ListNode head = res;
while(l1 != null && l2 != null) {
if(l1.val > l2.val) {
head.next = new ListNode(l2.val);
head = head.next;
l2 = l2.next;
} else {
head.next = new ListNode(l1.val);
head = head.next;
l1 = l1.next;
}
}
if(l1 == null) {
while(l2 != null) {
head.next = new ListNode(l2.val);
head = head.next;
l2 = l2.next;
}
} else {
while(l1 != null) {
head.next = new ListNode(l1.val);
head = head.next;
l1 = l1.next;
}
}
return res;
}
}
2. 有n个点代表横坐标中的位置,起始点为0,终点为n - 1,中间可以忽略一个点。求0道n-1,要走过的最短距离。
输入:
4
1,4,-1,3
输出:
4
暴力破解
package 笔试.youzan;
import java.util.Scanner;
public class Main1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] nums = splitDemo(scan.next().split(","));
int res = 0;
for(int i = 1; i < n; i++) {
res += Math.abs(nums[i] - nums[i - 1]);
}
for(int i = 1; i < n - 1; i++) {
int sum = 0;
int flag = nums[0];
for(int j = 1; j < n; j++) {
if(i == j) {
continue;
}
sum += Math.abs(nums[j] - flag);
flag = nums[j];
}
if(res > sum) {
res = sum;
}
}
System.out.println(res);
}
private static int[] splitDemo(String[] s) {
int[] nums = new int[s.length];
if(s == null || s.length == 0) {
return new int[0];
}
for(int i = 0; i < s.length; i++) {
nums[i] = Integer.valueOf(s[i]);
}
return nums;
}
}