数组
1、数组遍历
485.数组485.最大连续1的个数
数组485.最大连续1的个数
class Solution { public int findMaxConsecutiveOnes(int[] nums) { int max=0; int f_max=0; for(int i=0;i<nums.length;i++){ if(nums[i]==1){ max++; } else{ if(max>f_max){ f_max=max; } max=0; } } return f_max>max?f_max:max; } }
495. 提莫攻击
495. 提莫攻击
class Solution { public int findPoisonedDuration(int[] timeSeries, int duration) { int sum=0; for (int i=0;i<timeSeries.length;i++){ if(i<timeSeries.length-1){ if(timeSeries[i+1]-timeSeries[i]<duration){ sum+=timeSeries[i+1]-timeSeries[i]; } else{ sum+=duration; } } else{ sum+=duration; } } return sum; } }
414.第三大的数
第三大的数
class Solution { public int thirdMax(int[] nums) { Arrays.sort(nums); Integer one=null,two=null,third=null; if(nums.length<3){ return nums[nums.length-1]; } else{ one = nums[nums.length-1]; for(int i=nums.length-1;i>=0;i--){ if(nums[i]<one){ two=nums[i]; break; } } for(int i=nums.length-1;i>=0;i--){ if(two!=null){ if(nums[i]<two){ third=nums[i]; break; } } } } return third==null?one:third; } }
628.三个数的最大乘积
三个数的最大乘积
class Solution { public int maximumProduct(int[] nums) { Arrays.sort(nums); return Math.max(nums[0] * nums[1] * nums[nums.length - 1], nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3]); } }
统计数组中的元素
645.错误的集合
错误的集合
class Solution { public static int[] findErrorNums(int[] nums) { Arrays.sort(nums); int dup = -1, missing = 1; for (int i = 1; i < nums.length; i++) { if (nums[i] == nums[i - 1]){ dup = nums[i]; } else if (nums[i] > nums[i - 1] + 1) missing = nums[i - 1] + 1; } return new int[]{dup, nums[nums.length - 1] != nums.length ? nums.length : missing}; } }
697.数组的度
数组的度
class Solution { public static int findShortestSubArray(int[] nums) { Map<Integer, Integer> left = new HashMap(), right = new HashMap(), count = new HashMap(); for (int i = 0; i < nums.length; i++) { int x = nums[i]; if (left.get(x) == null) left.put(x, i); right.put(x, i); count.put(x, count.getOrDefault(x, 0) + 1); } int ans = nums.length; int degree = Collections.max(count.values()); for (int x : count.keySet()) { if (count.get(x) == degree) { ans = Math.min(ans, right.get(x) - left.get(x) + 1); } } return ans; } }
448.找到所有数组中消失的数字
找到所有数组中消失的数字
class Solution { public List<Integer> findDisappearedNumbers(int[] nums) { int [] arr=new int [nums.length+1]; int count=0; for(int i=0;i<nums.length;i++){ arr[nums[i]]++; } List<Integer> list=new ArrayList<Integer>(); for(int i=1;i<arr.length;i++){ if(arr[i]==0) list.add(i); } return list; } }
442.数组中重复的数据
数组中重复的数据
class Solution { public List<Integer> findDuplicates(int[] nums) { int [] arr=new int [nums.length+1]; int count=0; for(int i=0;i<nums.length;i++){ arr[nums[i]]++; } List<Integer> list=new ArrayList<Integer>(); for(int i=1;i<arr.length;i++){ if(arr[i]>1) list.add(i); } return list; } }