C语言 | Leetcode C语言题解之第525题连续数组
题目:
题解:
struct HashTable {int key, val;UT_hash_handle hh;
};int findMaxLength(int* nums, int numsSize) {int maxLength = 0;struct HashTable* hashTable = NULL;struct HashTable* tmp = malloc(sizeof(struct HashTable));tmp->key = 0, tmp->val = -1;HASH_ADD_INT(hashTable, key, tmp);int counter = 0;int n = numsSize;for (int i = 0; i < n; i++) {int num = nums[i];if (num == 1) {counter++;} else {counter--;}HASH_FIND_INT(hashTable, &counter, tmp);if (tmp != NULL) {int prevIndex = tmp->val;maxLength = fmax(maxLength, i - prevIndex);} else {tmp = malloc(sizeof(struct HashTable));tmp->key = counter, tmp->val = i;HASH_ADD_INT(hashTable, key, tmp);}}return maxLength;
}