In Python we do for loop like:
for i in range(len(nums))
In java: we have:
for (int i = 0; i < nums.length; i++)
Are these two for loop identical? If we made some change within the for loop, let's say in the for loop i has been plus 3, for Java, next i in for loop will be 4? while Python still start i from 2
Leetcode 594. Longest Harmonious Subsequence.
We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1
The solution written in Java as follow:
nums=[1,3,2,2,5,2,3,7]
public class Solution {
public int findLHS(int[] nums) {
Arrays.sort(nums);
int prev_count = 1, res = 0;
for (int i = 0; i < nums.length; i++) {
int count = 1;
if (i > 0 && nums[i] - nums[i - 1] == 1) {
while (i < nums.length - 1 && nums[i] == nums[i + 1]) {
count++;
i++;
}
res = Math.max(res, count + prev_count);
prev_count = count;
} else {
while (i < nums.length - 1 && nums[i] == nums[i + 1]) {
count++;
i++;
}
prev_count = count;
}
}
return res;
}
}
I converted to Python:
nums=[1,3,2,2,5,2,3,7]
nums=sorted(nums)
prev_count=1
res=0
i=0
for i in range(len(nums)-1):
count=1
if i>0 and nums[i]-nums[i-1]==1:
while i<len(nums)-1 and nums[i] == nums[i+1]:
count+=1
i+=1
res=max(res,count+prev_count)
prev_count=count
else:
while i<len(nums)-1 and nums[i] == nums[i+1]:
count+=1
i+=1
prev_count=count
print (res)
In Java
for (int i = 0; i < nums.length; i++) {
int count = 1;
if (i > 0 && nums[i] - nums[i - 1] == 1) {
while (i < nums.length - 1 && nums[i] == nums[i + 1]) {
count++;
i++;
}
i++ inside for loop so the i started from whatever i has been added.
In Python:
for i in range(len(nums)-1):
count=1
if i>0 and nums[i]-nums[i-1]==1:
while i<len(nums)-1 and nums[i] == nums[i+1]:
count+=1
i+=1
after i+=1, it only applied to While loop, for loop still start from i=2 not 4 instead.
Java returns answer as 5 while python is 4. I debug the code and looks like Java start i for whatever i has been added while Python didn't take added i and always start for last i.