Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to find minimum distance between two numbers in an array with Java

1 Answer

0 votes
public class MyClass {
    public static int MinDistance(int[] arr, int number1, int number2) {
        int size = arr.length;
 
        int min_distance = Integer.MAX_VALUE;
 
        for (int i = 0; i < size; i++) {
            for (int j = i + 1; j < size; j++) {
                if (arr[i] == number1 && arr[j] == number2 || 
                    arr[i] == number2 && arr[j] == number1) {
                    min_distance = Math.min(min_distance, Math.abs(i - j));
                }
            }
        }
 
        return min_distance;
    }
    public static void main(String args[]) {
        int[] arr = {2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3};
 
        System.out.println(MinDistance(arr, 3, 8));
    }
}
 
 
 
 
/*
run:
   
2
   
*/

 



answered Aug 24, 2022 by avibootz
edited Aug 24, 2022 by avibootz

Related questions

...