GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode-2/java/904_Fruit_Into_Baskets.java at master · ning609/leetcode-2 Expand file tree/ Copy path904_Fruit_Into_Baskets.javaMore file actions 73 lines (60 loc) · 2.18 KB / Copy path904_Fruit_Into_Baskets.javaFile metadata and controls73 lines (60 loc) · 2.18 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 class Solution { // https://leetcode.com/problems/fruit-into-baskets/solution/ /* public int totalFruit(int[] tree) { // We'll make a list of indexes for which a block starts. List<Integer> blockLefts = new ArrayList(); // Add the left boundary of each block for (int i = 0; i < tree.length; ++i) if (i == 0 || tree[i-1] != tree[i]) blockLefts.add(i); // Add tree.length as a sentinel for convenience blockLefts.add(tree.length); int ans = 0, i = 0; search: while (true) { // We'll start our scan at block[i]. // types : the different values of tree[i] seen // weight : the total number of trees represented // by blocks under consideration Set<Integer> types = new HashSet(); int weight = 0; // For each block from the i-th and going forward, for (int j = i; j < blockLefts.size() - 1; ++j) { // Add each block to consideration types.add(tree[blockLefts.get(j)]); weight += blockLefts.get(j+1) - blockLefts.get(j); // If we have 3+ types, this is an illegal subarray if (types.size() >= 3) { i = j - 1; continue search; } // If it is a legal subarray, record the answer ans = Math.max(ans, weight); } break; } return ans; }*/ public int totalFruit(int[] tree) { int ans = 0, i = 0; Counter count = new Counter(); for (int j = 0; j < tree.length; ++j) { count.add(tree[j], 1); while (count.size() >= 3) { count.add(tree[i], -1); if (count.get(tree[i]) == 0) count.remove(tree[i]); i++; } ans = Math.max(ans, j - i + 1); } return ans; } } class Counter extends HashMap<Integer, Integer> { public int get(int k) { return containsKey(k) ? super.get(k) : 0; } public void add(int k, int v) { put(k, get(k) + v); } } |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |