输入一组未排序的整数,找出其中最长的连续数字的长度。例如输入为[3,1,2,5,7,4,8,9] ,其中连续的数据为1,2,3,4,5,长度为5 。要求算法时间复杂度为O(n).
思路:存到hashset里面,然后依次遍历,如果当前数为连续数字的起始数字(即num-1不属于set),那么就开始往后看
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
s = s.substring(1,s.length()-1);
String[] strs = s.split(",");
int[] a = new int[strs.length];
HashSet<Integer> set = new HashSet<>();
int b = 0;
while(b<a.length){
a[b] = Integer.parseInt(strs[b]);
set.add(a[b++]);
}
int max = 0;
int cur = 0;
for(int i = 0;i<a.length;i++){
if(!set.contains(a[i]-1)){
cur = 0;
int tmp = a[i];
while(set.contains(tmp)){
cur++;
tmp++;
}
if(cur>max) max = cur;
}
}
System.out.println(max);
}
}
41. First Missing Positive
Given an unsorted integer array, find the smallest missing positive integer.
思路:如果都有序,那么第一个数字为1,第二个数字为2......第n个数字为n
class Solution {
public int firstMissingPositive(int[] nums) {
int end = nums.length;
if(end == 0) return 1;
int left = 0;
while(left<end){
if(nums[left] == left+1||nums[left]<=0||nums[left]>end) left++;
else if(nums[nums[left] - 1]!=nums[left]){
int temp = nums[nums[left] - 1];
nums[nums[left] - 1] = nums[left];
nums[left] = temp;
}
else left++;
}
int i = 0;
while(i<end&&nums[i]==i+1) i++;
return i+1;
}
}
152. Maximum Product Subarray
Given an integer array nums
, find the contiguous subarray within an array (containing at least one number) which has the largest product.
class Solution {
public int maxProduct(int[] nums) {
if(nums == null||nums.length == 0){
return 0;
}
int max = nums[0];
int min = nums[0];
int res = nums[0];
for(int i = 1;i<nums.length;i++){
int a = nums[i]*min;
int b = nums[i]*max;
max = Math.max(Math.max(a,b),nums[i]);
min = Math.min(Math.min(a,b),nums[i]);
if(max>res){
res = max;
}
}
return res;
}
}
53. Maximum Subarray
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
class Solution {
public int maxSubArray(int[] nums) {
if(nums == null||nums.length == 0) return 0;
int max = nums[0];
int cur = 0;
for(int i = 0;i<nums.length;i++){
cur=Math.max(nums[i],cur+nums[i]);
max = Math.max(cur,max);
}
return max;
}
}