LeetCode_904 Fruit Into Baskets

In a row of trees, the i-th tree produces fruit with type tree[i].

You start at any tree of your choice, then repeatedly perform the following steps:

  1. Add one piece of fruit from this tree to your baskets.  If you cannot, stop.
  2. Move to the next tree to the right of the current tree.  If there is no tree to the right, stop.

Note that you do not have any choice after the initial choice of starting tree: you must perform step 1, then step 2, then back to step 1, then step 2, and so on until you stop.

You have two baskets, and each basket can carry any quantity of fruit, but you want each basket to only carry one type of fruit each.

What is the total amount of fruit you can collect with this procedure?

Example 1:

Input: [1,2,1]
Output: 3
Explanation: We can collect [1,2,1].

Example 2:

Input: [0,1,2,2]
Output: 3
Explanation: We can collect [1,2,2].
If we started at the first tree, we would only collect [0, 1].

Example 3:

Input: [1,2,3,2,2]
Output: 4
Explanation: We can collect [2,3,2,2].
If we started at the first tree, we would only collect [1, 2].

Example 4:

Input: [3,3,3,1,2,1,1,2,3,3,4]
Output: 5
Explanation: We can collect [1,2,1,1,2].
If we started at the first tree or the eighth tree, we would only collect 4 fruits.

我的解题思路(思路有点混乱嘻嘻嘻):题目的本意就是从数组下标为i = 0开始依此扫描每个元素,扫描过程中把第一种数字(0~9分别为9种数字)放进第一篮子,把第二种数字放进第二篮子里面,每次扫描这两种数字,都会count加1(count是总共扫描的次数,count = 0),碰到第三种数字就会停止,就把count放进另外的数组array里面。接下来从下标为i = 1开始扫面,记录两种数字一共连续扫描多少次,然后把count放进array里面,以此类推。如果一直扫描到数组的最后元素,直接把count放进array数组中然后退出循环。那就不用再扫描下标为i++的元素了,因为再扫描的话没有比当前count更大的数了。

刚接触题目的时候就看懂了,但是具体不知道用什么方法实现,看了网上几个大佬的代码,自己始终没办法理解,不知道是不是智商问题(哈哈哈),所以还是自己慢慢的写出来,感觉很乱,凑合凑合看下。

注意:两个for是实现不了的,因为会超时,时间复杂度O(n^2)

下面附上我的代码

public class Solution {
    public static int totalFruit(int[] tree) {
        int temp;//记录arr数组的最大值
		int first = -1;//当刚开始扫描的时候记录当前的i,以便可以跳到下标i继续扫描
		int count = 0;//记录总共扫描的次数
		int a = -1;//第一种数字
		int sum = 1;//记录第几种数字
		int b = -1;//第二种数字
		int c = 0;//数组arr的下标
        int [] arr = new int[100000];
        if(tree.length == 1)
            return 1;
        for(int i = 0; i < tree.length; i++){
			if(count == 0){
				first = i;//先把这个下标记录,等到扫描终止时跳到first + 1下标
				a = tree[i];
				count++;
				continue;
			}
			if(sum == 1 && tree[i] != a){
				b = tree[i];
				sum++;
			}
	//当碰到第三种数字时候,记录count,然后把一些变量归为初值时然后跳到first + 1下标继续扫描
			if(sum == 3){
				arr[c++] = count;
				i = first;
				count = 0;
				b = -1;
				sum = 1;
				continue;
			}
			if(tree[i] != a && tree[i] != b){
				sum++;
			}
			else{
				count++;	
			}
			if(i == tree.length - 1)
            //如果一直扫描到最后就可以记录count,后面的下标最大的count值也就为count - 1
				arr[c++] = count;
        }
            //求出最大的count
			temp = arr[0];
			for(int j = 1; j <= c; j++){
				if(arr[j] > temp)
					temp = arr[j];
			}
			return temp;
    }
}

哎,人家大佬几行代码就搞定的事,我用了几十行,还需要再继续努力

猜你喜欢

转载自blog.csdn.net/Qgf_666/article/details/82784405
今日推荐