Problem:
Consider the leftmost and righmost appearances of some value in an array. We'll say that the "span" is the number of elements between the two inclusive. A single value has a span of 1. Returns the largest span found in the given array. (Efficiency is not a priority.)
maxSpan({1, 2, 1, 1, 3}) → 4
maxSpan({1, 4, 2, 1, 4, 1, 4}) → 6
maxSpan({1, 4, 2, 1, 4, 4, 4}) → 6
Solution:
public int maxSpan(int[] nums) { int span = 0; int tmp = 0; for (int i = 0; i < nums.length; i++) { for (int j = 0; j < nums.length; j++) { if (nums[i] == nums[j]) { tmp = j-i+1; span = Math.max(tmp,span); } } } return span; }
if(nums.length <1) return 0;
ReplyDeleteint span = 0;
for(int i=0; ii; j--){
if(nums[i] == nums[j]){
span = j-i > span ? j-i : span;
}
}
}
return span +1;
public int maxSpan(int[] nums) {
Deleteif(nums.length <1) return 0;
int span = 0;
for(int i=0; ii; j--){
if(nums[i] == nums[j]){
span = j-i > span ? j-i : span;
}
}
}
return span +1;
}
public int maxSpan(int[] nums) {
ReplyDeleteif(nums.length>0&&nums[0]!=nums[nums.length-1])
{
return nums.length-1;
}
return nums.length;
}
i like it :)
DeleteWith simple logic:
ReplyDeletepublic int maxSpan(int[] nums) {
int counter = 0;
if(nums.length == 0) {
return 0;
}
if(nums[0] != nums[nums.length - 1]) {
for(int i = 1; i < nums.length; i++) {
counter++;
}
}
if(nums[0] == nums[nums.length - 1]) {
for(int i = 0; i < nums.length; i++) {
counter++;
}
}
return counter;
}
public int maxSpan(int[] nums) {
ReplyDeleteif(nums.length<=1) return nums.length;
if(nums[0]==nums[nums.length-1]) return nums.length;
return nums.length - 1;
}
It only works for the few tests at coding bat. It's wrong as a solution, if you run your code for int[]{1, 4, 2, 1, 4, 4, 3} it returns 6 which is wrong. The correct answer is 5.
Deletepublic int maxSpan(int[] nums) {
ReplyDeleteint count = 0;
if (nums.length<=0) {
return 0;
}
for (int i = 0; i < nums.length; i++) {
for (int j = nums.length - 1; j >= 0; j--) {
if (nums[i] == nums[j]) {
if (j - i > count) {
count = j - i;
}
}
}
}
return count+1;
public int maxSpan(int[] nums) {
ReplyDeleteint max = Math.min(nums.length, 1);
for (int i = 0; i < nums.length; i++) {
for (int j = nums.length - 1 ; j > i; j--) {
if (nums[i] == nums[j]) max = Math.max(j - i + 1 ,max);
}
}
return max ;
}
public int maxSpan(int[] nums) {
ReplyDeleteint max = 0;
for (int i = 0; i < nums.length; i++) {
int j = nums.length - 1;
while (j > i && nums[j] != nums[i]) {
j--;
}
max = Math.max(max, j - i + 1);
}
return max;
}
all the point is to use 2 loops to practise.. idk what ya doin
ReplyDelete