【力扣leetcode】-881. 救生艇

package leetcode;

import java.util.Arrays;
import java.util.Collections;

/* 
Author:Samba
Time :2021年8月26日
Data:下午2:08:25
*/
//救生艇
public class t881 {
	public static void main(String[] args) {
		Solution881 s = new Solution881();
		int[] list = {5,1,7,4,2,4};
		int result = s.numRescueBoats_02(list, 7);
		System.out.println(result);
	}

}

class Solution881 {
	//方法一:	双循环、标记+枚举
    public int numRescueBoats_01(int[] people, int limit) { 	
    	int[] flag = new int[people.length];
    	Integer[] list = new Integer[people.length];
    	for(int i=0;i<people.length;i++){
    		list[i]= new Integer(people[i]);
		}
    	Arrays.fill(flag, 0);
    	Arrays.sort(list,Collections.reverseOrder());
    	int result = 0;
    	for (int i =0;i<list.length;i++) {
			//首先判断是否已被处理
    		if(flag[i] == 0) {
    			if(i == list.length-1) {
    				flag[i] = 1;
    				result+=1;
    			}else {
    				boolean isFind = false;
        			for(int j = i+1;j<list.length;j++) {
        				//如果满足条件并且未被处理则处理掉
        				if(list[i] + list[j] <= limit&&flag[j]==0) {
        					flag[i] = 1;
        					flag[j] = 1;
        					result+=1;
        					isFind = true;
        					break;
        				}
        			}
        			if(!isFind) {
        				flag[i] = 1;
        				result+=1;
        			}
    			}
    			
    		}
		}
    	return result;
    }
    
    
    //方法二:	单循环、双游标
    public int numRescueBoats_02(int[] people, int limit) { 
    	Arrays.sort(people);
    	int result = 0;
    	//设置游标 i,j
    	int i = 0,j=people.length-1;
    	while(i<j) {
    		if(people[i]+people[j]<=limit) {
    			result+=1;
    			i++;j--;
    		}else {
    			result+=1;
    			j--;
    		}
    	}
    	//i与j相等说明有个独苗被留下来了
    	if(i==j) {
    		result+=1;
    	}
    	return result;
    }
}

  

posted @ 2021-08-26 15:27  BIGBIGGUAI  阅读(24)  评论(0编辑  收藏  举报