简体   繁体   中英

finds two numbers in an array with the smallest distance to each other In Java

One question from a website: Implement a Java function that finds two numbers in an array with the smallest distance to each other. The function should return the index of the first number.

Here is my thoughts. But I don't know how to implement it.

  1. Step1. Get all the result of 2 element arrays from a given array. For example {4,5,7,11} have 4*3 = 12 two element arrays.
  2. Step2. Calculate each the two array distance. And find out the minimum distance.

I do viewed at least 10 google results. Seems don't have the good answer. IN real life, people would first sort it then try some way to figure it out. But let's assume the array as it is. We do not sort it. The following code is based on one expert's answer. But unfortunately it seems not working...

import java.math.*;
import java.util.*;
import java.util.Arrays;
import java.util.Collections;

public class TestallBasics1 {
    public static void main(String[] args) {
        int[] arr = new int[]{2,1,6,8,10,89,54};
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));

        int difference=0;
        int n = arr.length;
        for(int i=0; i<n-1; i++){
            if(difference > (arr[i+1]-arr[i]))
            {difference = arr[i+1]-arr[i];}

        System.out.println(difference);

        }
    }
}

I found out the answer online. Brillant!

public int getIndexOfMinimumDistance() {
    int index = 0;
    int[] numbers = new int[]{999,0,5,8,10,89,54};

    for (int i = 1; i < numbers.length - 1; i++) {
        if ( Math.abs( numbers[index] - numbers[index + 1]) >
            Math.abs( numbers[i] - numbers[i + 1])) {
            index = i;
        }
    }

step1: sort the array by applying any technique or using any predefined methods. Arrays.sort() , Collections.sort etc. which is applicable. step2: Iterate the elements and find the difference between the current and next element, store the difference in a variable and update it when the difference is smaller than the current.

int difference=0;
for(int i=0; i<n-1; i++){
    if(difference > (arr[i+1]-arr[i])){
        difference = arr[i+1]-arr[i];
    }
}

now you will have the smallest distance in difference variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM