二分查找
请实现有重复数字的有序数组的二分查找。
输出在数组中第一个大于等于查找值的位置,如果数组中不存在这样的数,则输出数组长度加一。
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int v = in.nextInt();
int[] arr=new int[n];
for(int i=0;i<arr.length;i++){
arr[i]=in.nextInt();
}
int l=0;
int r=arr.length-1;
while(l <= r) {
int mid = l + (r - l) / 2;
if(arr[mid] < v) {
l = mid + 1;
} else {
r = mid - 1;
}
}
// If l is within the bounds of the array and arr[l] is the first element
// greater than or equal to v, return l + 1, since the question assumes
// 1-based indexing. If no such element exists, return the length of the
// array plus one.
System.out.print(l < arr.length && arr[l] >= v ? l + 1 : arr.length + 1);
}
}
无穷大二叉树的最近公共祖先
有一棵无穷大的满二叉树,其结点按根结点一层一层地从左往右依次编号,根结点编号为1。现在有两个结点a,b。请设计一个算法,求出a和b点的最近公共祖先的编号。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n1 = in.nextInt();
int n2 = in.nextInt();
int ancestor = findLowestCommonAncestor(n1, n2);
System.out.println(ancestor);
}
public static int findLowestCommonAncestor(int n1, int n2) {
while (n1 != n2) {
if (n1 > n2) {
n1 /= 2;
} else {
n2 /= 2;
}
}
return n1;
}
}
牛牛的链表交换
牛牛尝试把一个长度为 n 的数组转换成链表并把链表前两个节点交换位置和把链表最后两个节点交换位置。
import java.util.*;
public class Main {
public static class ListNode {
public int val;
public ListNode next;
public ListNode(int val) {
this.val = val;
this.next = null;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
ListNode head = new ListNode(0);
ListNode current = head;
ListNode two = null; // 声明和定义two节点
for (int i = 0; i < n; i++) {
ListNode p = new ListNode(in.nextInt());
current.next = p;
current = current.next;
}
ListNode p = head.next;
ListNode q = head.next.next;
p.next=q.next;
head.next = q;
q.next = p;
int i=0;
while(head.next!=null){
if(i<n-2)
System.out.print(head.next.val+" ");
if(i==n-2) {
two=head.next;
System.out.print(two.next.val+" ");
}
if(i==n-1) System.out.print(two.val+" ");
head=head.next;
i++;
}
}
}