engeloded
BAN USERTime: O(n). Space: O(1).
public static void swap(Integer[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static Integer[] reverse(Integer[] arr, int n) {
int parts = arr.length/n;
int k;
int j;
for(int i=0;i<parts;i++) {
k=n-1;
j=0;
while(j<k) {
if((i*n+k)>=arr.length) {
k--;
}else {
swap(arr,i*n+(j++), i*n+(k--));
}
}
}
return arr;
}
O(m+n) solution s.t. m is first array's length and n is the second's array length
public static Integer[] merge(Integer[] arr1, Integer[] arr2) {
int n = arr1.length+arr2.length;
Integer[] arr = new Integer[n];
int arr1Index = 0;
int arr2Index = 0;
for(int i=0;i<n;i++) {
if(arr1Index==arr1.length) {
arr[i] = arr2[arr2Index++];
} else if(arr2Index==arr2.length) {
arr[i] = arr1[arr1Index++];
} else if(arr1[arr1Index]<arr2[arr2Index]) {
arr[i] = arr1[arr1Index++];
} else {
arr[i] = arr2[arr2Index++];
}
}
return arr;
}
O(n) time complexity solution..
Here is my Java solution:
public static String compress(String s) {
if(s==null||s.length()<2) {
throw new IllegalArgumentException();
}
StringBuilder sb = new StringBuilder(s);
int sIndex = 0;
int currCnt=1;
char currChar = sb.charAt(0);
char nextChar;
for(int i=1;i<sb.length();i++) {
nextChar = sb.charAt(i);
if(nextChar==currChar) {
currCnt++;
}else {
sb.setCharAt(sIndex++, currChar);
sb.setCharAt(sIndex++, (""+currCnt).charAt(0));
currChar = nextChar;
currCnt=1;
}
}
sb.setCharAt(sIndex++, currChar);
sb.setCharAt(sIndex++, (""+currCnt).charAt(0));
sb.setLength(sIndex);
return sb.toString();
}
Repsusiejcrider, Member Technical Staff at Accolite software
I was a Communications Consultant with experience in working across various clients .technology, consumer, hospitality, financial services and corporate social ...
- engeloded November 28, 2017