LeetCode134. 加油站
思路:
主要是在遍历的时候计算局部剩余油量总和,如果小于0则说明无法走到需要更新起始点。
public int canCompleteCircuit(int[] gas, int[] cost) {
int start=0,sum=0,cur=0;
for(int i=0;i<gas.length;i++) {
//cur目前局部总和只要小于0则选下一个位置
cur+=gas[i]-cost[i];
sum+=gas[i]-cost[i];
if(cur<0) {
start=i+1;
cur=0;
}
}
if(sum<0) return -1;
return start;
}
LeetCode135. 分发糖果
思路:
主要是利用两次遍历,第一次遍历的时候需要给数组里的每个位置都填上值。第二次反向遍历的时候在根据(该位置的最大值,和后一位+1来判断)
public int candy(int[] ratings) {
int[] res = new int[ratings.length];
res[0]=1;
for(int i=1;i<ratings.length;i++) {
res[i]=(ratings[i]>ratings[i-1])?(res[i-1]+1):1;
}
for(int i=ratings.length-2;i>=0;i--) {
if (ratings[i] > ratings[i + 1]) {
res[i] = Math.max(res[i], res[i + 1] + 1);
}
}
int sum=0;
for(int i=0;i<res.length;i++) {
sum+=res[i];
}
return sum;
}
LeetCode860.柠檬水找零
public boolean lemonadeChange(int[] bills) {
int five=0,ten=0;
for(int i=0;i<bills.length;i++) {
if(bills[i]==5) {
five++;
}else if(bills[i]==10) {
ten++;
if(five==0)return false;
five--;
}else if(bills[i]==20) {
if(ten>=1&&five>=1) {
ten--;
five--;
}else if(five>=3) {
five=five-3;
}else {
return false;
}
}
}
return true;
}
LeetCode406.根据身高重建队列
public int[][] reconstructQueue(int[][] people) {
Arrays.sort(people, new Comparator<int[]>() {
public int compare(int[] person1, int[] person2) {
if (person1[0] != person2[0]) {
return person2[0] - person1[0];
} else {
return person1[1] - person2[1];
}
}
});
List<int[]> ans = new ArrayList<int[]>();
for (int[] person : people) {
ans.add(person[1], person);
}
return ans.toArray(new int[ans.size()][]);
}