如何在重复值的情况下找到最大的元素定位器

时间:2014-02-18 14:00:55

标签: java arrays

我需要找到最大的元素定位器。这段代码有效,但是如果我给出两次最大元素,那么我该如何返回两个位置呢?

import java.util.Scanner;

public class LargestElementLocator {

    public static void main(String[] args) {
        //Read the input from the console
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the number of rows and columns of the array: ");
        //Read no.of rows
        int rows  = input.nextInt();
        //Read no.of columns
        int columns = input.nextInt();

        //Create new array object
        double[][] a = new double[rows][columns];
        //Input array of elements
        System.out.println("Enter the array: ");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++)
            a[i][j] = input.nextDouble();
        }
        //call the locateLargest and print
        int[] location = locateLargest(rows,columns,a);
        System.out.println("The location of the largest element is at (" + location[0] + ", " + location[1] + ")");
    }

    //method to determine the max val & postion

    public static int[] locateLargest(int rows,int columns,double[][] a) {
        int[] location = new int[2];

        double largest = a[0][0];
        //rows = 10;
        //columns = 10;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                if (largest < a[i][j]) {
                    largest = a[i][j];
                    location[0] = i;
                    location[1] = j;
                }
            }
        }
        return location;
    }
}

4 个答案:

答案 0 :(得分:0)

我现在能想到的唯一方法是:

  1. 获得最大的数字。

  2. 在第二次迭代中,再次遍历数组以找出等于最大元素的位置。(虽然非常不优化的方法)

  3. 快速建议:您可以为{J} location创建一个getter/setter课程。对此我可以创建一个包含所有位置的HashSet保存位置对象。

答案 1 :(得分:0)

您可以使用数组列表存储最大的所有位置。像这样的东西。

import java.util.Scanner;
public class LargestElementLocator {

public static void main(String[] args)
{
    //Read the input from the console
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of rows and columns of the array: ");
//Read no.of rows
int rows  = input.nextInt();
//Read no.of columns
int columns = input.nextInt();

//Create new array object
double[][] a = new double[rows][columns];
//Input array of elements
System.out.println("Enter the array: ");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
a[i][j] = input.nextDouble();
}
//call the locateLargest and print
int[] location = locateLargest(rows,columns,a);
System.out.println("The location of the largest element is at (" + location[0] + ", " + location[1] + ")");
}

//method to determine the max val & postion

public static List<Location> locateLargest(int rows,int columns,double[][] a) {

double largest = a[0][0];
//rows = 10;
//columns = 10;
for (int i = 0; i < rows; i++) {
  for (int j = 0; j < columns; j++) {
    if (largest < a[i][j]) {
      largest = a[i][j];
    }
  }
}

List<Location> locations = new ArrayList<Location>();
for (int i = 0; i < rows; i++) {
  for (int j = 0; j < columns; j++) {
    if (largest = a[i][j]) {
      locations.add(new Location(i,j));
    }
  }
}

return locations;
}
}

class Location {
  int x,y;
  Location(int x, int y) {
      this.x = x;
      this.y = y;
  }
}

答案 2 :(得分:0)

以下代码完成了这项工作。我并不是说没有更好的办法,但我认为这是迄今为止我提出的最佳方式。

import java.util.ArrayList;
import java.util.Scanner;

public class LargestElementLocator {

    public static void main(String[] args) {
        //Read the input from the console
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the number of rows and columns of the array: ");
        //Read no.of rows
        int rows  = input.nextInt();
        //Read no.of columns
        int columns = input.nextInt();

        //Create new array object
        double[][] a = new double[rows][columns];
        //Input array of elements
        System.out.println("Enter the array: ");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++)
            a[i][j] = input.nextDouble();
        }
        //call locateLargest
        ArrayList[] location = locateLargest(rows,columns,a);
        // check how many largest elements there are and print
        if(location[0].size()==1)
        {
            System.out.println("The location of the largest element is at (" + location[0].get(0) + ", " + location[1].get(0) + ")");
        }
        else if(location[0].size()>1)
        {
            for(int i=0;i<location[0].size();i++)
            {
            System.out.println("The location of the largest element number "+i+": (" + location[0].get(i) + ", " + location[1].get(i) + ")");
            }
        }

    }

    //method to determine the max val & postion

    public static ArrayList[] locateLargest(int rows,int columns,double[][] a) {

        ArrayList[] location = new ArrayList[2];
        location[0] = new ArrayList(); // to hold row position/s of the largest element/s
        location[1] = new ArrayList(); // to hold column position/s of the largest element/s

        double largest = a[0][0];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {

                if (largest < a[i][j]) {
                    // a new maximum element has been discovered so get rid 
                    // of any previously stored maxima positions
                    location[0].clear();
                    location[1].clear();
                    largest = a[i][j];
                    // ArrayLists can't hold primitives, so wrap i and j in Integers
                    Integer I = new Integer(i);
                    Integer J = new Integer(j);
                    // store row and column positions of this maximum
                    location[0].add(I);
                    location[1].add(J);
                }

                else if (largest == a[i][j]) {
                    // a duplicate maximum has been found, so add 
                    // its row  and column positions to the list
                    largest = a[i][j];
                    Integer I = new Integer(i);
                    Integer J = new Integer(j);
                    location[0].add(I);
                    location[1].add(J);
                }

            }
        }

        return location;

    }
}

它确实使用了一些无类型的ArrayLists数组,Eclipse警告它们需要进行参数化,但它运行正常。如果您不想在代码中添加任何警告,可以使用2dArrayList替换ArrayList数组:这是我使用过的2dArrayList类:

import java.util.ArrayList;

class ArrayList2d<T> {

ArrayList<ArrayList<T>> array;

    public ArrayList2d() {

        array = new ArrayList<ArrayList<T>>();

    }

/**
     * ensures a minimum capacity of num rows. Note that this does not guarantee
     * that there are that many rows.
     * 
     * @param num
     */
    public void ensureCapacity(int num)
    {
        array.ensureCapacity(num);
    }

    /**
     * Ensures that the given row has at least the given capacity. Note that
     * this method will also ensure that getNumRows() >= row
     * 
     * @param row
     * @param num
     */
    public void ensureCapacity(int row, int num)
    {
        ensureCapacity(row);
        while (row < getNumRows())
        {
            array.add(new ArrayList<T>());
        }
        array.get(row).ensureCapacity(num);
    }

    /**
     * Adds an item at the end of the specified row. This will guarantee that at least row rows exist.
     */
    public void Add(T data, int row)
    {
        ensureCapacity(row);
        while(row >= getNumRows())
        {
            array.add(new ArrayList<T>());
        }
        array.get(row).add(data);
    }

    public T get(int row, int col)
    {
        return array.get(row).get(col);
    }

        public ArrayList getRow(int row)
        {
                return array.get(row);
        }

        public ArrayList getCol(int column)
        {
                ArrayList result = new ArrayList();
                for(int i=0;i<array.size();i++)
                {   
                    result.add(array.get(i).get(column));
                }
                return result;
        }

    public void set(int row, int col, T data)
    {
        array.get(row).set(col,data);
    }

    public void remove(int row, int col)
    {
        array.get(row).remove(col);
    }

    public boolean contains(T data)
    {
        for (int i = 0; i < array.size(); i++)
        {
            if (array.get(i).contains(data))
            {
                return true;
            }
        }
        return false;
    }

    public int getNumRows()
    {
        return array.size();
    }

    public int getNumCols(int row)
    {
        return array.get(row).size();
    }
}

答案 3 :(得分:0)

你可以用高效的方法做到: -

首先在数组中存储第一个元素的位置及其值(用于检查条件),如果元素相同并且存储了元素,则检查所有其他元素在一个数组中,然后将它存储在下一个空元素中,如果元素更大比数组中存在的元素那么只需创建新数组并重复上面的过程直到行*列并且不要触摸数组。