0

Say I have an int array called sequence with values

[1, 3, 2, 4, 3, 5, 4, 6, 1, 3]

I want to check if another instance of 1 exists besides the first one in the array, and if it does, I would like to get its index in the array.

So far, this is what I've done:

// Get the first and second number of the sequence array
int firstNumberIndex = 0;
int firstNumber = sequence[0];
int secondNumber = sequence[1];
// Check that firstNumber < secondNumber
if (firstNumber < secondNumber) {
    // Remove firstNumber from the sequence array
    instance = removeElement(sequence, firstNumberIndex);
    // Check whether another instance of
    // firstNumber exists in sequence array
    if (contains(sequence, firstNumber)) {
        // Here, I would like to get the index of
        // the other instance of '1', for example
    }
}
2
  • Is 1 an arbitrary number or is it always the first element? Commented Apr 23, 2021 at 21:25
  • @Bohemian I want to find another occurrence of the first element in the array. In this case, since 1 is the first element, I want to find the index of its other occurrences Commented Apr 24, 2021 at 0:20

3 Answers 3

2

Preferring readability over raw execution speed:

List<Integer> list = new ArrayList<>();
IntStream.of(sequence).forEach(list::add);
int index = list.subList(1, list.size()).indexOf(sequence[0]) + 1;

See live demo.

index will be 0 if no second occurrence exists.

Sign up to request clarification or add additional context in comments.

Comments

1

a fast answer uses a hash:

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Snippet {
    public static void main(String[] args) {
        int[] sequence = {1, 3, 2, 4, 3, 5, 4, 6, 1, 3};
        Map<Integer, List<Integer>> indexMap = new LinkedHashMap<>();
        for (int i = 0; i < sequence.length; i++) {
            int val = sequence[i];
            indexMap.computeIfAbsent(val, k -> new ArrayList<>()).add(i);
        }
        System.out.println(indexMap);
    }
}

output:

{1=[0, 8], 3=[1, 4, 9], 2=[2], 4=[3, 6], 5=[5], 6=[7]}

So it gives for every value in the sequence all the indexes at which this value is found, which may or may not be more than what the OP asked for.

The values are returned in order encountered (thanks to LinkedHashMap), and the indexes are sorted. Overall it is O(length of the sequence) in time.

Comments

0
  1. You can use List#indexOf method two times to get the second occurrence of an object in the List<Integer>:
    public static int getSecond(List<Integer> list, int val) {
        // index of the first occurrence
        int i = list.indexOf(val);
        // if found and not the last one
        if (i > -1 && i < list.size() - 1) {
            // index of the second occurrence from
            // the sublist after the first occurrence
            int j = list.subList(i + 1, list.size()).indexOf(val);
            // if found, return the composite index
            if (j > -1) return j + i + 1;
        }
        // not found
        return -1;
    }
    
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 3, 2, 4, 3, 5, 4, 6, 1, 3);
        System.out.println(getSecond(list, 3)); // 4
        System.out.println(getSecond(list, 1)); // 8
        System.out.println(getSecond(list, 6)); // -1
        System.out.println(getSecond(list, 7)); // -1
    }
    
  2. You can use IntStream if only an array int[] is required:
    public static int getSecond(int[] arr, int val) {
        return IntStream
                // iterating over array indices
                .range(0, arr.length)
                // filter the search elements
                .filter(i -> arr[i] == val)
                // skip the first one
                .skip(1)
                // take the second one
                .findFirst()
                // if not found
                .orElse(-1);
    }
    
    public static void main(String[] args) {
        int[] arr = {1, 3, 2, 4, 3, 5, 4, 6, 1, 3};
        System.out.println(getSecond(arr, 3)); // 4
        System.out.println(getSecond(arr, 1)); // 8
        System.out.println(getSecond(arr, 6)); // -1
        System.out.println(getSecond(arr, 7)); // -1
    }
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.