《重启20》
java算法-找出数组最大三个数(利用Integer.MIN_VALUE解决)&&两个有序数组整合为一个有序数组(双指针)
题目:
从一个给定的数组中选出最大的三个数,且不能使用排序算法。
public class Main {
public static void main(String[] args) {
int[] arr = {-1, 10, 29, 1, 65, 78, 3, 15, 15, 18, -6, 11};
int[] nums = new int[3];
int max = Integer.MIN_VALUE;//java中最小的整数
int index = -1;
//循环三次找到三个最大数
for(int j = 0; j < 3; j++) {
for(int i = 0; i < arr.length; i++) {
if(arr[i] > max) {
max = arr[i];
index = i;
}
}
nums[j] = max;
arr[index] = Integer.MIN_VALUE;
max = Integer.MIN_VALUE;
}
//输出
for(int i : nums)
System.out.print(i);
}
}
ps:Integer.MIN_VALUE为java中最小整数为: -2147483648
题目:
两个有序数组整合为一个有序数组
public class Main {
//假设数组是递增数组
public static int[] mergeLikeSort(int[] arr1, int[] arr2) {
int[] res=new int[arr1.length+arr2.length];
int index1=0; //arr1的指针
int index2=0; //arr2的指针
for(int i=0;i<res.length;i++){
if(index1<arr1.length&&index2<arr2.length){
if(arr1[index1]<arr2[index2]){
res[i]=arr1[index1];
index1++;
}else if (arr1[index1]>arr2[index2]){
res[i]=arr2[index2];
index2++;
}
//如果要消除重复值的情况就要加上index2++;
else if(arr1[index1]==arr2[index2]){
res[i]=arr1[index1];
index1++;
}
}else if(index1<arr1.length){
res[i]=arr1[index1];
index1++;
}else if(index2<arr2.length){
res[i]=arr2[index2];
index2++;
}
}
return res;
}
public static void main(String[] args) {
int[] res=mergeLikeSort(new int[]{1, 3, 4, 5, 7, 8},new int[]{1,2,3,4});
for (int i:res){
System.out.print(i+" ");
}
}
}