LmaoSuVuong
Senior Member
Nhận ra dùng array code hơi nhọc tí nhưng chạy phải nhanh gấp đôi so với hashmapJava:public static int numberOfSubarrays(int[] nums, int k) { int count,res; int i; int first = curr = 0; int iRight = 1; int curr = 0; curLeft = curRight =count = res= 0; int[] left = new int[nums.length+1]; int[] right = new int[nums.length+1]; for(i=0; i<nums.length;i++){ if(nums[i]%2==1){ count++; if(count == 1) first = i; left[count] = i-curr; curr = i; } if(count==k) { break; } } if(first ==0) left[1] = 1; else left[1]++; if(count!=k) return 0; i++; Arrays.fill(right, 1); for(int j =i; j<nums.length;j++){ if(nums[j]%2==0) right[iRight]++; else { res+= left[iRight]*right[iRight]; left[k+iRight]=right[iRight]; iRight++; } } res+= left[iRight]*right[iRight]; return res; }
![]()
cùng là O(1) nhưng là access phần tử trong array chỉ tốn 1 phép tínhừ thì access time đều là O(1) cả mà dùng array bao giờ cũng nhanh hơn đhs.![]()
access trong hash map phải đi qua các bước hash, compare, check này nọ 5-6 phép tính vẫn là O(1), gọi n lần thì chậm hơn đúng r fen,
![gnnOU6Q.png](/proxy.php?image=https%3A%2F%2Fi.imgur.com%2FgnnOU6Q.png&hash=b95a6626d8cf4992be75ac5522d6ddc0)