Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

525. Contiguous Array #111

Open
Tcdian opened this issue Apr 13, 2020 · 1 comment
Open

525. Contiguous Array #111

Tcdian opened this issue Apr 13, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Apr 13, 2020

525. Contiguous Array

给定一个二进制数组, 找到含有相同数量的 0 和 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.
@Tcdian
Copy link
Owner Author

Tcdian commented Apr 13, 2020

Solution

  • JavaScript Solution
/**
 * @param {number[]} nums
 * @return {number}
 */
var findMaxLength = function(nums) {
    let prefix = 0;
    let result = 0;
    const cache = new Map([[prefix, -1]]);
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] === 1) {
            prefix += 1;
        } else {
            prefix -= 1;
        }
        if (cache.has(prefix)) {
            result = Math.max(result, i - cache.get(prefix));
        } else {
            cache.set(prefix, i);
        }
    }
    return result;
};
  • TypeScript Solution
var findMaxLength = function(nums: number[]): number {
    let prefix = 0;
    let result = 0;
    const cache = new Map([[prefix, -1]]);
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] === 1) {
            prefix += 1;
        } else {
            prefix -= 1;
        }
        if (cache.has(prefix)) {
            result = Math.max(result, i - (cache.get(prefix) as number));
        } else {
            cache.set(prefix, i);
        }
    }
    return result;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant