Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Hashmaps: Longest consecutive Sequence #11

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 33 additions & 61 deletions Hashmaps:Longest consecutive Sequence
Original file line number Diff line number Diff line change
@@ -1,65 +1,37 @@



import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Arrays;

public class Solution {
public static ArrayList<Integer> longestConsecutiveIncreasingSequence(int[] arr) {
HashMap<Integer,Boolean> map = new HashMap<>();
ArrayList<Integer> output = new ArrayList<>();

for(int i=0;i<arr.length;i++){
map.put(arr[i],true);
}

int maxlength = 0;
int start = 0;

for(int i=0;i<arr.length;i++){
if(map.get(arr[i])){
int length = 0;
int temp = arr[i];
while(map.containsKey(temp)){
length++;
map.put(temp,false);
temp = temp+1;
}
int starttemp = arr[i];
temp = arr[i]-1;
while(map.containsKey(temp)){
length++;
map.put(temp,false);
starttemp = temp;
temp = temp-1;
}

if(length > maxlength){
maxlength = length;
start = starttemp;
}else if(length == maxlength){
maxlength = length;
//start = 10 starttemp = 4
for(int j=0;j<arr.length;j++){
if(arr[j] == start){
start = start;
break;
}else if(arr[j] == starttemp){
start = starttemp;
break;
}
}
}
}
// else{
// continue;
// }
}

for(int i = start;i<start+maxlength;i++){
output.add(i);
}

return output;

}

/* Your class should be named Solution
* Don't write main().
* Don't read input, it is passed as function argument.
* Return output and don't print it.
* Taking input and printing output is handled automatically.
*/
HashMap<Integer,Integer> map=new HashMap<>();
ArrayList<Integer> arrayList=new ArrayList<>();
ArrayList<Integer> arrayListcopy=new ArrayList<>();
for(int i=0;i<arr.length;i++){
map.put(arr[i], arr[i]);
}
for(int i=0;i<arr.length;i++){
int j=0;
while(map.containsKey(arr[i]+j)){
arrayListcopy.add(arr[i]+j);
j++;
}
if(arrayListcopy.size()>arrayList.size()){
arrayList=arrayListcopy;
}
arrayListcopy=new ArrayList<>();
}
ArrayList<Integer> output=new ArrayList<>();
output.add(arrayList.get(0));
output.add(arrayList.get(arrayList.size()-1));

return output;
}
}