Each integer appears exactly once except A which appears twice and B which is missing. - Java Algorithm

Java examples for Algorithm:Number

Introduction

You are given a read only array of n integers from 1 to n.

Each integer appears exactly once except A which appears twice and B which is missing.

Return A and B.

Note that in your output A should precede B.

Demo Code


import java.util.*;

public class App {

    public static void main(String[] args) {
        Integer[] arr = {3, 1, 2, 5, 3};
        List<Integer> rslt;

        rslt = new Solution().repeatedNumberByEquation(Arrays.asList(arr));
        for (int i = 0; i < rslt.size(); ++i) {
            System.out.print(rslt.get(i) + " ");
        }/*w  w w  .j  a  v  a 2s . co  m*/
        System.out.println();

        rslt = new Solution().repeatedNumberByArrPosition(Arrays.asList(arr));
        for (int i = 0; i < rslt.size(); ++i) {
            System.out.print(rslt.get(i) + " ");
        }
        System.out.println();
    }
}

class Solution {

    // O(n)
    public List<Integer> repeatedNumberByEquation(List<Integer> arr) {
        List<Integer> rslt = new ArrayList<>();

        long sum = 0, squareSum = 0;
        for (int i = 0; i < arr.size(); ++i) {
            sum += arr.get(i);
            sum -= (i + 1);
            squareSum += arr.get(i) * arr.get(i);
            squareSum -= (i + 1) * (i + 1);
        }

        // x - repeating, y - missing
        int x, y;

        // (x - y)
        long xmy = sum;
        // (x^2 - y^2) / (x - y) = ((x - y) * (x + y)) / (x - y) = (x + y)
        long xpy = squareSum / sum;

        x = (int) ((xmy + xpy) / 2);
        y = (int) (xpy - x);

        rslt.add(x);
        rslt.add(y);

        return rslt;
    }

    // O(n)
    public List<Integer> repeatedNumberByArrPosition(List<Integer> arr) {
        List<Integer> rslt = new ArrayList<>();

        for (int i = 0; i < arr.size(); ++i) {
            int k = Math.abs(arr.get(i));

            if (arr.get(k - 1) > 0) {
                arr.set(k - 1, -arr.get(k - 1));
            } else {
                rslt.add(k);        
            }
        }

        for (int i = 0; i < arr.size(); ++i) {
            if (arr.get(i) > 0) {
                rslt.add(i + 1);
            }
        }

        return rslt;
    }
}

Related Tutorials