image.png

    1. package Normal;
    2. import java.util.HashMap;
    3. import java.util.Map;
    4. public class ContinuousArray_0_1 {
    5. public static int findMaxLength(int[] nums) {
    6. //连续子数组长度
    7. int maxLength = 0;
    8. //哈希表
    9. Map<Integer,Integer> map = new HashMap<Integer, Integer>();
    10. //计数
    11. int count = 0;
    12. //将0和1的连续子数组长度问题,转化为-1和1的元素和问题,0位置的0转为-1
    13. map.put(count,-1);
    14. //遍历数组
    15. for(int i = 0;i<nums.length;i++){
    16. int num = nums[i];
    17. //为1则++
    18. if(num == 1){
    19. count++;
    20. }else{//反之则--
    21. count--;
    22. }
    23. //如果map中包含count当前的值,则取出count在哈希表中对应的下标preIndex
    24. //nums从下标preIndex+1到i的子数组中有相同的0和1
    25. //该子数组的长度为i-preIndex
    26. //使用该数组的长度更新最长子数组的长度
    27. if(map.containsKey(count)){
    28. //将map中count的值赋给前缀和
    29. int preIndex = map.get(count);
    30. maxLength = Math.max(maxLength,i-preIndex);
    31. }else{//如果count的值不被包含于map中,则将当前余数和当前下标i的值放到map中
    32. map.put(count,i);
    33. }
    34. }
    35. return maxLength;
    36. }
    37. public static void main(String[] args){
    38. int[] nums = new int[]{0,1,0,1};
    39. System.out.println(findMaxLength(nums));
    40. }
    41. }

    image.png