用數組代表每個人的能力一個比賽活動要求 參賽團隊的最低能力值為N,每個團隊可以由一人或者兩人組成
且一個人只能參加一個團隊,計算出最多可以派出多少只符合要求的隊伍
輸入描述
5
3 1 5 7 9
8
第一行代表總人數,范圍 1~500000
第二行數組代表每個人的能力,數組大小范圍 1~500000,元素取值范圍 1~500000
第三行數值為團隊要求的最低能力值,1~500000
輸出描述
3
最多可以派出的團隊數量
示例一
輸入
5
3 1 5 7 9
8
輸出
3
說明 3、5組成一隊 1、7一隊 9自己一隊 輸出3
查看代碼
import java.util.*;
public class Demo28 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int people = Integer.parseInt(sc.nextLine());
String[] split = sc.nextLine().split(" ");
int require = Integer.parseInt(sc.nextLine());
int len = split.length;
int[] ints = new int[len];
for(int i = 0; i < len; i++){
ints[i] = Integer.parseInt(split[i]);
}
Arrays.sort(ints);
int count = 0;
//用下標來處理,真妙啊
int left = 0, right = len - 1;
while(left < right){
if(ints[right] >= require){
count++;
right--;
}else{
if(ints[left] + ints[right] >= require){
count++;
left++;
right--;
}else left++;
}
}
System.out.println(count);
}
}
總結:這種用下標處理問題的方式要好好感受,為解題思路增添動力。
