Algorithm problem

Given an unordered array arr, return the length of the longest sequence of consecutive numbers (1,2,3,4)

Example 1

Input {100,4,200,1,3,2}

The output of 4

Example 2 input {200201202100,4,200,1,3,2,204,203}

The output of 5

import java.util.Scanner; import java.util.*; import java.lang.Integer; Public class Main {public static void Main (String[] args) {Scanner Scanner = new Scanner(system.in); String lineStr = scanner.nextLine(); String[] elements =lineStr.split(" "); Vector<Integer> list = new Vector<Integer>(); for(int i=0; i<elements.length; <i++){ list.add(Integer.parseInt(elements[i])); } Collections.sort(list); int targetLen = 0; int startNum = list.get(0); int currentMaxLen=1; for(int k=1; k<list.size(); k++){ if(list.get(k) == startNum+1){ currentMaxLen = currentMaxLen + 1; }else{if(currentMaxLen>targetLen){ } startNum = list.get(k); } } System.out.println(targetLen); }}Copy the code

1, OOM online processing

2. Project status of encryption scheme and electronic signature

3, the principle of distributed lock, Zookeeper, Redis distributed lock

4. Redis underlying data structure

5. Principle of Spring AOP

6. Message queue usage

7. Big data processing

8. The underlying principles of HashMap

9. Reasons for changing jobs

10, MQ message loss problem processing

11. Bluetooth communication protocol

12. Split the project micro-service and its principle

Summary: the algorithm of the scene is still wrong, the interviewer prompts after adding a judgment condition, or wrong. The modification is as follows

package test;

import java.util.Scanner;
import java.util.*;
import java.lang.Integer;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		String lineStr = scanner.nextLine();
		String[] elements = lineStr.split(" ");
		List<Integer> list = new ArrayList<Integer>();
		for (int i = 0; i < elements.length; i++) {
			Integer val = Integer.parseInt(elements[i]);
			if(!list.contains(val)){
				list.add(val);
			}
		}
		Collections.sort(list);
		System.out.println(list);
		int targetLen = 0;
		int startNum = list.get(0);
		int currentMaxLen = 1;
		for (int k = 1; k < list.size(); k++) {
			int e = list.get(k);
			startNum = startNum + 1;
			if ( e == startNum) {
				currentMaxLen = currentMaxLen + 1;
			} else {
				if (currentMaxLen > targetLen) {
					targetLen = currentMaxLen;
				}
				startNum = list.get(k);
				currentMaxLen = 1;
				System.out.println(startNum);
			}
			
			if(k == list.size()-1){
				if (currentMaxLen > targetLen) {
					targetLen = currentMaxLen;
				}
			}
		}
		System.out.println(targetLen);
	}
}
Copy the code