簡體   English   中英

如何在java中的整數數組中找到整數的重復序列?

[英]How to find repeating sequence of Integers in an array of Integers in java?

例如,如果輸入是:

2 0 6 3 1 6 3 1 6 3 1

那么輸出應該是6 3 1.需要找到第一個重復周期。

class FindDuplicate
{
void printRepeating(int arr[], int size)
{
    int i; 
    System.out.println("The repeating elements are : ");

    for (i = 0; i < size; i++)
    {
        if (arr[Math.abs(arr[i])] >= 0)
            arr[Math.abs(arr[i])] = -arr[Math.abs(arr[i])];
        else
            System.out.print(Math.abs(arr[i]) + " ");
    }        
} 


public static void main(String[] args) 
{
    FindDuplicate duplicate = new FindDuplicate();
    int arr[] = {1, 2, 3, 1, 2, 3, 1, 2, 3 };
    int arr_size = arr.length;
    duplicate.printRepeating(arr, arr_size);
}
}

https://pastebin.com/12bnjzfw已使用 java 8 流進行集合創建。

for (int seqSize = ints.size() / 2; seqSize > 0; seqSize--) { //It should be first cycle. Main priority is biggest sequence
  for (int i = 0; i < ints.size() / seqSize; i++) { //Start position of the first block
    for (int j = i + seqSize; j < ints.size() - seqSize + 1; j++) {
      if (ints.subList(i, i + seqSize).equals(ints.subList(j, j + seqSize))) {
        System.out.println("Answer is: " + ints.subList(i, i + seqSize));
        return;
      }
    }
  }
}

例如,循環遍歷這些數組元素並緩存您的元素,直到您具有相同的值

List list = Arrays.asList(1,2,3);
if(list.contains(element))
 //code to check here

您將需要獲取列表的大小,並根據該大小檢查這些項目是否匹配,如果是,則輸出如果不清除緩存並從請求開始緩存。

class FindDuplicate {
    static int STRING_LENGTH = 3;

    void printRepeating(int arr[], int size) {
        int i; 
        System.out.println("The repeating elements are : ");
        String strVal = "";
        for (int ii = 0; ii < size; ii++) {
            strVal += arr[ii]; 
        }
        // strVal now has something we can search with.

        for (i = 0; i < size; i++) {
            int end = Math.min(size,i+STRING_LENGTH );
            String searchString = strVal.substring(i, end);
            if (searchString.length() != STRING_LENGTH)
                break;  // at end of arr, doesn't have length to search 
            int matchIndex = strVal.indexOf(searchString, i+1);
            if (matchIndex != -1) {
               String match = strVal.substring(matchIndex, matchIndex + STRING_LENGTH);
               System.out.print(match + " ");
               break; // done with loop
            }
        }        
    } 


    public static void main(String[] args) {
        FindDuplicate duplicate = new FindDuplicate();
        int arr[] = {1, 2, 3, 1, 2, 3, 1, 2, 3 };
        int arr_size = arr.length;
        duplicate.printRepeating(arr, arr_size);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM