前缀和
import java.util.HashMap;
import java.util.Map;
public class Test3 {
public static void main(String[] args) {
int[] nums={0,1,0};
Test3 test3=new Test3();
int maxLength = test3.findMaxLength(nums);
System.out.println(maxLength);
}
public int findMaxLength(int[] nums) {
int[] preSum=new int[nums.length+1];
//第一个存前i个数和 第二个存下标
//最大值为下标减去下标
Map<Integer,Integer> map=new HashMap<>();
map.put(0,0);
//preSum[i]为nums 前i个和
for (int i = 1; i <=nums.length; i++) {
preSum[i]=preSum[i-1]+(nums[i-1]==1?1:-1);
}
int max=0;
for (int i = 1; i <preSum.length ; i++) {
int value=preSum[i];
if (!map.containsKey(value)){
map.put(value,i);
}else {
max=Math.max(max,i-map.get(value));
}
}
return max;
}
}
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode pA = headA, pB = headB;
while (pA != pB) {
pA = pA == null ? headB : pA.next;
pB = pB == null ? headA : pB.next;
}
return pA;
}