A local maximum is an element that is greater than any of its neighboring elements. You must remove elements that are local maxima in the original array.
Input array:
[18, 1, 3, 6, 7, -5]
output array:
[1, 3, 6, -5]
public static int[] removeLocalMaxima(int[] array){
int[] result = new int[array.length];
int j = 0;
for (int i = 0; i < array.length - 1; i++, j++) {
if(array[i] > array[i + 1]){
result[j] = array[++i];
}else {
result[j] = array[i];
}
}
return Arrays.copyOf(result, j);
}
if you set it like that, then something is not working:
array = new int[1000];
Arrays.fill(array, 15);
array[0] = -20;
array[999] = 25;
array[168] = 18;
array[421] = 0;
actual = LocalMaximaRemove.removeLocalMaxima(array);
assertEquals(998, actual.length);
assertEquals(-20, actual[0]);
assertEquals(15, actual[997]);
assertEquals(0, actual[420]);
public static int[] removeLocalMaxima(int[] array){
int[] result = new int[array.length];
int j = 0;
for (int i = 0; i < array.length; i++) {
if ((i > 0 && array[i] <= array[i - 1])
|| (i != array.length - 1 && array[i] <= array[i + 1])){
result[j++] = array[i];
}
}
return Arrays.copyOf(result, j);
}
My function saves in result array only elements that are less or equal of any of its neightbors.
I want to perform a linear search though a[] and append the result to b[].
Here is my code:
public class sorting {
static int a[]={10,12,14,2,1,3};
static int b[]=new int[a.length];
public static void fn()
{
for(int i=0;i<a.length;i++)
{
for(int j=1;j<a.length;j++)
{
if(a[i]>a[j]){
b[i]=a[j];
}
}
}
}
I am getting output as 333101. I expect {1,2,8,10,12,30}.
Even after finding 1 as minimum, loop continues and find 10>3 and replaces 1 with 3. How do I stop the loop when a minimum is found?
You never initialize b[0] if a[0] is the smallest value in a.
If you want to have a sorted Output in b you should probably to a compare including bin the if statement.
What would be the intended behaviour if some numbers are negative or multipe times in a?
One possible approach similar to your code would be
public static void fn() {
for (int i = 0; i < a.length; i++) {
b[i] = Integer.MAX_VALUE; // initialize with large value
for (int j = 0; j < a.length; j++) {
// search for Minimum bigger than last value already in b
if (b[i] > a[j] && (i == 0 || a[j] > b[i - 1])) {
b[i] = a[j];
}
}
}
}
Try this approach.
public class Main
{
public static void main (String[]args)
{
int a[] = { 10, 12, 14, 2, 1, 3 }, c;
int b[] = new int[a.length];
b = a;
for (int i = 0; i < b.length; i++)
{
for (int j = i + 1; j < b.length; j++)
{
if (b[i] > b[j])
{
c = b[i];
b[i] = b[j];
b[j] = c;
}
}
}
for (int j = 0; j < b.length; j++)
{
if (j == 0)
{
System.out.print ("{"+b[j]+",");
}else if(j == b.length-1){
System.out.print(b[j]+"}");
}else{
System.out.print(b[j]+",");
}
}
}
}
output:{1,2,3,10,12,14}
For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The goal is to rotate array A K times;
that is, each element of A will be shifted to the right by K indexes.
For example, given array A = [3, 8, 9, 7, 6] and K = 3, the function should return [9, 7, 6, 3, 8].
I want this in java.
I have tried this.
public static int[] rotation(int[] a,int k) {
int[] newArray = new int[a.length];
for(int i = 0 ; i < a.length ; i++) {
int newPosition = (i + k)%a.length;
newArray[newPosition] = a[i];
}
return newArray;
}
I didnt get what exactly wants topic starter but here my code for this task
class Solution {
public int[] solution(int[] arr, int k) {
int[] newArr = new int[arr.length];
if (arr.length == 0) return arr;
k = k%arr.length;
for (int i=0; i<arr.length; i++) {
newArr[i] = arr[(i + (arr.length - k)) % (arr.length)];
}
return newArr;
}
}
You can also use A = B.clone();
public int[] solution(int[] A, int K) {
// write your code in Java SE 8
int [] B =new int [A.length];
for(int l=0;K>l;K--){
int j=0;
for(int i=0;i<A.length;i++){
if(i==0){
B[j]=A[A.length-1];
j++;
}
else{
B[j]=A[i-1];
j++;
}
}
//below part
/*for(int i= 0;i<A.length;i++){
A[i]=B[i];
}*/
A = B.clone();
}
return B;
}
If you like :D
You can print the result using Arrays.toString. For example:
System.out.println(Arrays.toString(rotation(new int[] { 3, 8, 9, 7, 6}, 3)));
public int[] solution(int[] A, int K) {
// write your code in Java SE 8
int [] B =new int [A.length];
for(int l=0;K>l;K--){
int j=0;
for(int i=0;i<A.length;i++){
if(i==0){
B[j]=A[A.length-1];
j++;
}
else{
B[j]=A[i-1];
j++;
}
}
for(int i= 0;i<A.length;i++){
A[i]=B[i];
}
}
return B;
}
function solution(A, K) {
function shiftArray(arrayToShift, newArray=[] ){
newArray[0] = arrayToShift[arrayToShift.length-1] ;
for (var i=1; i<arrayToShift.length; i++){
newArray[i] = arrayToShift[i-1];
}
// console.log("arrayToShift");
// console.log(newArray);
return newArray;
}
var newArray = A;
for(var i=0; i<K; i++){
newArray = shiftArray(newArray);
}
return newArray
}
console.log(solution([3, 8, 9, 7, 6], 3));
Achieved 100% correctness
public int[] solution(int[] A, int K) {
// write your code in Java SE 8
if(K == A.length || A.length == 0)
return A;
if(K > A.length) {
K = K%A.length;
}
int[] arr1 = Arrays.copyOfRange(A, A.length-K, A.length);
int[] arr2 = Arrays.copyOfRange(A, 0, A.length-K);
int aLen = arr1.length;
int bLen = arr2.length;
int[] result = new int[aLen + bLen];
System.arraycopy(arr1, 0, result, 0, aLen);
System.arraycopy(arr2, 0, result, aLen, bLen);
return result;
}
Here's my solution using JavaScript, tested 100%.
function solution(A, K) {
for(let i=0; i<K; i++) {
let lastIndex = A.length - 1;
let lastItem = A[lastIndex];
for(let j=(A.length-1); j>-1; j--) {
if(j>0) {
A[j] = A[j-1];
} else {
A[j] = lastItem;
}
}
}
return A;
}
class Solution {
public int[] solution(int[] A, int K){
if((A.length == 0) || (K == 0)){
return A;
}
int [] B = new int[A.length];
int c = K;
while(c != 0){
for(int i = 1; i< A.length; i++){
B[i] = A[i-1];
}
c--;
B[0] = A[A.length-1];
System.arraycopy(B, 0, A, 0, A.length);
}
return A;
}
}
In Kotlin:
fun flipList(list: List<Int>, times: Int): List<Int> {
val flippedList = list.toMutableList()
val referenceList = list.toMutableList()
repeat(times) {
var position = 0
referenceList.forEach {
position++
if (position < list.size)
flippedList[position] = referenceList[position -1]
else
flippedList[0] = referenceList.last()
}
referenceList.clear()
referenceList.addAll(flippedList)
}
return flippedList
}
Unit Teste
class FlipListUnitTest {
private val referenceListMock = listOf(1,2,3,4)
private val referenceListOneTimeFlipResultMock = listOf(4,1,2,3)
private val referenceListFourTimesFlipResultMock = listOf(1,2,3,4)
#Test
fun `check test api is working`(){
assertTrue(true)
}
#Test
fun `check list flip 1 time`(){
assertTrue(flipList(referenceListMock, 1) == referenceListOneTimeFlipResultMock)
}
#Test
fun `check list flip 4 time`(){
assertTrue(flipList(referenceListMock, 4) == referenceListFourTimesFlipResultMock)
}
}
Here in my code
public static int[] solution(int[] A, int K){
if(A.length > 0) {
for(int i = 0; i < K ; i++){
int temp = A[A.length - 1];
for(int j = A.length - 2; j >= 0; j--){
A[j + 1] = A[j];
}
A[0] = temp;
}
}
return A;
}
public static int[] solution(int[] A, int K) {
if(A.length<1)
return A;
int[] newArray = new int[A.length];
while (K>0){
newArray[0]=A[A.length-1];
for(int i=0; i<A.length-1; i++){
newArray[i+1]=A[i];
}
for (int i=0; i<newArray.length; i++) {
A[i]=newArray[i];
}
K--;
}
return A;
}
An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place.
Hi everyone here is another simple solution for this problem in JAVA, 100% working.
class Solution {
public int[] solution(int[] A, int K) {
// Corner cases to save resources
if(K == 0 || A.length <= 0 || A.length == K){
return A;
}
// Loop to traverse K times
for(int i=0; i<K; i++){
int last = A[A.length - 1]; // Last digit
// Loop to traverse A.Length times in swing order,
// so that first element can be set
for(int j=A.length-1; j>0; j--){
A[j] = A[j-1];
}
// Set last element
A[0] = last;
}
// Return result
return A;
}
}
Here is my answer in JavaScript
function solution(A, K){
let arr = [];
let lastIndex = A.length -1;
let rotation = K-1;
for(let i = 0; i < K; i++){
arr[rotation] = A[lastIndex];
--lastIndex;
--rotation;
}
for(let j = 0; j <= lastIndex; j++){
arr.push(A[j]);
}
return arr;
}
Here is my answer in Python without loop and using string substitution
def solution(A, K):
K = K % len(A) if K > len(A) else K
if (K == 0) or (K == len(A)) or (len(A) in [0, 1]):
return A
first_index = len(A) - K
return A[first_index:] + A[:first_index]
function solution(A, K) {
let tmpA = [];
for (let i = 1; i <= K; i++){
tmpA.unshift(A.pop());
}
for (let i = 1; i <= K; i++){
A.unshift(tmpA.pop());
}
return A;
}
This is the code written in PHP but logic can be used in any language.
function solution($A, $K) {
// write your code in PHP7.0
$cnt = count($A);
for($i=1; $i<=$K; $i++){
foreach($A as $key=>$val){
$key++;
if($key==$cnt){
$A[0] = $val;
}
else
{
$A[$key] = $val;
}
}
}
return $A;
}
javascript | score: 100%
function solution(A, K) {
for(let i=0 ; i<K ; i++){
let lastIndex = A.length-1;
let lastNumber = A[lastIndex];
A.unshift(lastNumber);
A.pop();
}
return A;
}
public static int[] rotateArrayKTimes(int[] A, int K) {
if (A.length == 0 || A.length > 1000 || K > 100) {
return new int[]{};
}
for (int index = 0; index < K; index++) {
int temp = A[A.length - 1];
System.arraycopy(A, 0, A, 1, A.length - 1);
A[0] = temp;
}
return A;
}
JAVA solution -
class Solution2 {
public int[] solution(int[] arr, int k) {
int temp;
int startindex = 0;
if (arr.length != 0) {
for (int i = 1; i <= k; i++) {
temp = arr[arr.length - 1];
for (int j = arr.length - 1; j >= startindex; j--) {
if (j != (startindex)) {
arr[j] = arr[j - 1];
} else
arr[startindex] = temp;
}
}
} else
System.out.println("This is empty array");
return arr;
}
}
The following code counts inversions in an array nums (pairs i,j such that j>i && nums[i] > nums[j]) by merge sort.
Is it possible to use the same approach to count the number of special inversions like j>i && nums[i] > 2*nums[j]?
How should I modify this code?
public static void main (String args[])
{
int[] nums = {9, 16, 1, 2, 3, 4, 5, 6};
System.out.println("Strong Inversions: " + countInv(nums));
}
public static int countInv(int nums[])
{
int mid = nums.length/2;
int countL, countR, countMerge;
if(nums.length <= 1)
{
return 0;
}
int left[] = new int[mid];
int right[] = new int[nums.length - mid];
for(int i = 0; i < mid; i++)
{
left[i] = nums[i];
}
for(int i = 0; i < nums.length - mid; i++)
{
right[i] = nums[mid+i];
}
countL = countInv (left);
countR = countInv (right);
int mergedResult[] = new int[nums.length];
countMerge = mergeCount (left, right, mergedResult);
for(int i = 0; i < nums.length; i++)
{
nums[i] = mergedResult[i];
}
return (countL + countR + countMerge);
}
public static int mergeCount (int left[], int right[], int merged[])
{
int a = 0, b = 0, counter = 0, index=0;
while ( ( a < left.length) && (b < right.length) )
{
if(left[a] <= right[b])
{
merged [index] = left[a++];
}
else
{
merged [index] = right[b++];
counter += left.length - a;
}
index++;
}
if(a == left.length)
{
for (int i = b; i < right.length; i++)
{
merged [index++] = right[i];
}
}
else
{
for (int i = a; i < left.length; i++)
{
merged [index++] = left[i];
}
}
return counter;
}
I tried this
while ((a < left.length) && (b < right.length)) {
if (left[a] <= right[b]) {
merged[index] = left[a++];
} else {
if (left[a] > 2 * right[b]) {
counter += left.length - a;
}
merged[index] = right[b++];
}
index++;
}
but there's a bug in the while loop, when left[a]<2*right[b] but left[a+n] maybe>2*right[b], for instance left array is {9,16} and right array is {5,6}, 9<2*5 but 16>2*5. My code just skip cases like this and the result number is less than it should be
The while loop in mergeCount serves two functions: merge left and right into merged, and count the number of left–right inversions. For special inversions, the easiest thing would be to split the loop into two, counting the inversions first and then merging. The new trigger for counting inversions would be left[a] > 2*right[b].
The reason for having two loops is that counting special inversions needs to merge left with 2*right, and sorting needs to merge left with right. It might be possible to use three different indexes in a single loop, but the logic would be more complicated.
while ( ( a < left.length) && (b < right.length) ) {
if(left[a] <= right[b]) {
merged [index] = left[a++];
} else {
counter += updateCounter(right[b],a,left);
merged [index] = right[b++];
}
index++;
//Rest of the while loop
}
//Rest of the mergeCount function
}
public static int updateCounter(int toSwitch, int index, int[] array) {
while(index < array.length) {
if(array[index] >= 2*toSwitch)
break;
index++;
}
return array.length-index;
}
Not very efficient, but it should do the work. You initialise index with a, because elements lower than a will never will never meet the condition.
I am trying to move all non-zero integers to the beginning/left-side of the array 'a.'(for example {0,0,4,3,0} becomes {4,3,0,0,0})
This is my program. It compiles and runs with no errors but the array ends up with only zeros. Any suggestions would be appreciated.
int[] squeezeLeft(int[] a) {
int count = 0;
//creates new array
int [] a2 = new int[a.length];
//loops through a
for (int i = 0; i< a.length; i++){
//gets a temporary value from a[i]
int temp = a[i];
//assigns a[i] to temporary variable
a[count] = temp;
a[i] = 0;
/* raises count integer by one, so the following indice which is zero, is replaced
by the following non=zero integer*/
count++;
}
return a2;
}
I know this is not very efficient solution O^2 but it will do what you are asking.
private static int[] sequeezeLeft(final int[] a) {
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
for (int j = 0; j < a.length; j++) {
if (a[j] == 0) {
a[j] = a[i];
a[i] = 0;
}
}
}
}
return a;
}
Another version with O(n) time complexity
private static int[] sqeeze2(int [] a){
int index = 0;
if(a.length == 0)
return a;
for(int i=0;i<a.length;i++){
if(a[i] !=0 && index < a.length){
a[index] = a[i];
a[i]=0;
index++;
}
}
return a;
}
Or if you are a bit lazy, what about using this?
Integer[] ints = new Integer[] { 0, 5, 2, 0, 1, 5, 6 };
List<Integer> list = Arrays.asList(ints);
Collections.sort(list);
Collections.reverse(list);
System.err.println(list); // prints [6, 5, 5, 2, 1, 0, 0]
Not sure about performance, though..
static void squeezeLeft(int[] array) {
int arrayIndex = 0;
if (array.length != 0) {//check the length of array whether it is zero or not
for (int i = 0; i < array.length; i++) {
if (array[i] != 0 && arrayIndex < array.length) {//check the non zero element of array
if (i != arrayIndex) {//if the index of non zero element not equal to array index
//only then swap the zero element and non zero element
array[arrayIndex] = array[i];
array[i] = 0;
}
arrayIndex++; //increase array index after finding non zero element
}
}
}
}
how about:
Arrays.sort(ints, new Comparator<Integer>() {
#Override
public int compare(Integer o1, Integer o2)
{
if (o1 == 0) return 1;
if (o2 != 0 && o1 > o2) return 1;
if (o2 != 0 && o1 == o2) return 0;
return -1;
}
});
As is for input 1,0,2,0,4,0,5,0,6,0 the second solution will fail as output will be:
0245600000
For o(n):
private static int[] reArrangeNonZeroElement(int arr[]) {
int count = 0;
if (arr.length == 0)
return arr;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
arr[count++] = arr[i];
}
}
for (; arr.length > count; ) {
arr[count++] = 0;
}
return arr;
}