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 — leet-code/Java/Contiguous Array.java at master · awangdev/leet-code Expand file tree/ Copy pathContiguous Array.javaMore file actions executable file ·76 lines (64 loc) · 2.03 KB / Copy pathContiguous Array.javaFile metadata and controlsexecutable file ·76 lines (64 loc) · 2.03 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 74 75 76 M 1531902072 tags: Hash Table TODO: how aout without chaning the input nums? ``` /* Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. Example 1: Input: [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. Example 2: Input: [0,1,0] Output: 2 Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. Note: The length of the given binary array will not exceed 50,000. */ /* k = sum - i - 1 check if map.containsKey(preSum - k). If so, Math.max(max, i - map.get(preSum - k)) */ class Solution { public int findMaxLength(int[] nums) { if (nums == null || nums.length == 0) return 0; for (int i = 0; i < nums.length; i++) { if (nums[i] == 0) nums[i] = -1; } Map<Integer, Integer> map = new HashMap<>(); map.put(0, -1); int preSum = 0, max = 0; for (int i = 0; i < nums.length; i++) { preSum += nums[i]; if (map.containsKey(preSum)) { max = Math.max(max, i - map.get(preSum)); } if (!map.containsKey(preSum)) { map.put(preSum, i); } } return max; } } // TODO: what if not reseting 0 -> -1, can we solve this? // Also, inspired by Buy/Sell Stock https://leetcode.com/problems/contiguous-array/discuss/99655/Python-O(n)-Solution-with-Visual-Explanation class Solution { public int findMaxLength(int[] nums) { if (nums == null || nums.length == 0) return 0; Map<Integer, Integer> map = new HashMap<>(); map.put(0, -1); int preSum = 0, max = 0; for (int i = 0; i < nums.length; i++) { preSum += nums[i]; int k = preSum - i - 1; if (map.containsKey(preSum - k)) { max = Math.max(max, i - map.get(preSum - k)); } if (!map.containsKey(preSum)) { map.put(preSum, i); } } return max; } } ``` |
| You are visitor 01402503 — 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. |