Java Array Unique uniqueInts(int[] ints)

Here you can find the source of uniqueInts(int[] ints)

Description

returns the unique values from the given int array in sort order.

License

Open Source License

Parameter

Parameter Description
ints the ints to pair down to a unique sorted list

Return

the unique sorted list

Declaration

public static int[] uniqueInts(int[] ints) 

Method Source Code

//package com.java2s;
/*//from  w w  w. j  a  v a  2s .  com
 * Copyright (c) 2010 The Jackson Laboratory
 * 
 * This is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this software.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.Arrays;

public class Main {
    /**
     * returns the unique values from the given int array in sort order.
     * this function sorts the given int array. if all of the given ints are
     * unique then a reference to the given object is returned
     * @param ints  the ints to pair down to a unique sorted list
     * @return      the unique sorted list
     */
    public static int[] uniqueInts(int[] ints) {
        Arrays.sort(ints);

        int duplicateCount = 0;
        for (int i = 1; i < ints.length; i++) {
            if (ints[i] == ints[i - 1]) {
                duplicateCount++;
            }
        }

        if (duplicateCount == 0) {
            return ints;
        } else {
            int[] uniqueInts = new int[ints.length - duplicateCount];
            uniqueInts[0] = ints[0];

            int j = 1;
            for (int i = 1; i < ints.length; i++) {
                if (uniqueInts[j - 1] != ints[i]) {
                    uniqueInts[j] = ints[i];
                    j++;
                }
            }

            assert j == uniqueInts.length;

            return uniqueInts;
        }
    }
}

Related

  1. invertRelabeling(int[] relabeling, int[] uniqueVars, int maxVarNum)
  2. unique(double[] in)
  3. unique(int[] a, int aLen, int[] b, int bLen)
  4. unique(int[] array)
  5. unique(Object[] elements)
  6. uniques(final int[] ints)