classSolution{publicintmaxProfit(int[] prices){int low =Integer.MAX_VALUE;int max =Integer.MIN_VALUE;for(int i =0; i < prices.length; i++){if(prices[i]<low) low = prices[i];
max =Math.max(prices[i]- low , max);}return max;}}
122
classSolution{publicintmaxProfit(int[] prices){int val =0;if(prices.length <2)return val;for(int i =1; i < prices.length; i++){if(prices[i]> prices[i-1]){//提高代码效率
val += prices[i]- prices[i-1];}}return val;}}
55
classSolution{publicbooleancanJump(int[] nums){int index =0;while(true){int length = nums[index];int max =Integer.MIN_VALUE;int maxIndex =0;for(int j = index +1; j <= index + length && j<nums.length ; j++){if(nums[j]+ j > max){
max = nums[j]+j;
maxIndex = j;}}if(nums[maxIndex]+maxIndex >= nums.length -1)returntrue;if(maxIndex ==0)returnfalse;
index = maxIndex;}}}
45
classSolution{publicintjump(int[] nums){int step =0;int index =0;while(index<nums.length-1){
step++;int length = nums[index];int max =0;int next = index;for(int i = length; i >=1; i--){if(index+i>=nums.length-1)return step;if(nums[index+i]+i>max){
next = index + i;
max = nums[index+i]+ i;}}
index = next;}return0;}}
classSolution{publicinthIndex(int[] citations){Arrays.sort(citations);int res =0;for(int i = citations.length -1;i>=0;i--){if(citations[i]>= citations.length - i){
res = citations.length - i;}}return res;}}
238
classSolution{publicint[]productExceptSelf(int[] nums){int[]L=newint[nums.length];int[]R=newint[nums.length];int[] answer =newint[nums.length];L[0]=1;for(int i =1; i < nums.length; i++){L[i]=L[i-1]*nums[i-1];}R[nums.length-1]=1;for(int i = nums.length-2; i >=0; i--){R[i]=R[i+1]*nums[i+1];}for(int i =0; i < nums.length; i++){
answer[i]=L[i]*R[i];}return answer;}}
classSolution{publicintromanToInt(String s){Map<Character,Integer> map =newHashMap<>();
map.put('I',1);
map.put('V',5);
map.put('X',10);
map.put('L',50);
map.put('C',100);
map.put('D',500);
map.put('M',1000);char[] chars = s.toCharArray();int res =0;for(int i =0; i < s.length(); i++){if(i<s.length()-1&&map.get(chars[i])<map.get(chars[i+1])) res-=map.get(chars[i]);else{
res+=map.get(chars[i]);}}return res;}}
12
classSolution{publicStringintToRoman(int num){int[] values ={1000,900,500,400,100,90,50,40,10,9,5,4,1};String[] symbols ={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};StringBuffer result =newStringBuffer();for(int i =0; i < symbols.length; i++){while(num>=values[i]){
num -= values[i];
result.append(symbols[i]);}if(num ==0)break;}return result.toString();}}
58
classSolution{publicintlengthOfLastWord(String s){String[] result = s.split(" ");return result[result.length -1].length();}}
14
classSolution{publicStringlongestCommonPrefix(String[] strs){int count = strs.length;int lenght = strs[0].length();for(int i =0; i < lenght; i++){char c = strs[0].charAt(i);for(int j =1; j < count; j++){if(i==strs[j].length()||c!=strs[j].charAt(i)){return strs[0].substring(0,i);}}}return strs[0];}}
classSolution{publicintstrStr(String haystack,String needle){int start =-1;int end =-1;
start = haystack.indexOf(needle);//字串首次出现位置
end = haystack.lastIndexOf(needle);//字串最后出现位置if(end!=-1){return start;}return-1;}}
双指针
125
classSolution{publicbooleanisPalindrome(String s){int left =0;int right = s.length()-1;while(left<right){while(left<right&&!Character.isLetterOrDigit(s.charAt(left))){
left++;}while(left<right&&!Character.isLetterOrDigit(s.charAt(right))){
right--;}if(left<right){if(Character.toLowerCase(s.charAt(left))!=Character.toLowerCase(s.charAt(right))){returnfalse;}
left++;
right--;}}returntrue;}}
392
classSolution{publicbooleanisSubsequence(String s,String t){char[] schar = s.toCharArray();char[] tchar = t.toCharArray();if(schar.length ==0)returntrue;int index =0;for(int i =0; i < tchar.length; i++){if(schar[index]==tchar[i]) index++;if(index==schar.length)returntrue;//注意这条语句在for循环里面,要不然index会越界}returnfalse;}}
167
classSolution{publicint[]twoSum(int[] numbers,int target){Map<Integer,Integer> hashMap =newHashMap<>();for(int i =0; i < numbers.length; i++){if(hashMap.containsKey(target - numbers[i])){returnnewint[]{hashMap.get(target - numbers[i])+1,i+1};}
hashMap.put(numbers[i],i);}returnnull;}}
11
classSolution{publicintmaxArea(int[] height){int left =0;int right = height.length-1;int res =0;while(left<right){
res =Math.max(res,(right-left)*Math.min(height[left],height[right]));if(height[left]<height[right]) left++;else right--;}return res;}}
15.三数之和
classSolution{publicList<List<Integer>>threeSum(int[] nums){Arrays.sort(nums);List<List<Integer>> res =newArrayList<>();for(int first =0; first < nums.length; first++){if(first>0&&nums[first]==nums[first-1])continue;int target =-nums[first];int third = nums.length-1;for(int second = first+1; second < nums.length; second++){if(second>first+1&&nums[second]==nums[second-1])continue;while(third>second&& nums[second]+nums[third]> target) third--;if(second == third)break;if(nums[second]+nums[third]== target){List<Integer> buffer =newArrayList<>();
buffer.add(nums[first]);
buffer.add(nums[second]);
buffer.add(nums[third]);
res.add(buffer);}}}return res;}}
滑动窗口
209
classSolution{publicintminSubArrayLen(int target,int[] nums){int left =0;int right =0;int sum =0;int shortest =Integer.MAX_VALUE;while(right<nums.length){
sum += nums[right++];if(sum>=target){while(true){
sum -= nums[left++];if(sum<target){
shortest =Math.min(shortest,right-left+1);break;}}}}return shortest ==Integer.MAX_VALUE?0:shortest;}}
3
classSolution{publicintlengthOfLongestSubstring(String s){char[] chars = s.toCharArray();HashMap<Character,Integer> hashMap =newHashMap<>();int left =0;int right =0;int longest =0;while(right<s.length()){if(hashMap.containsKey(chars[right])&&hashMap.get(chars[right])>=left){
left = hashMap.get(chars[right])+1;}
hashMap.put(chars[right],right);
right ++;
longest =Math.max(longest,right-left);}return longest;}}
矩阵
36
classSolution{publicbooleanisValidSudoku(char[][] board){int[][] rows =newint[9][9];int[][] cols =newint[9][9];int[][][] subboxes =newint[3][3][9];for(int i =0; i <9; i++){for(int j =0; j <9; j++){char c = board[i][j];if(c !='.'){int index = c -'0'-1;
rows[i][index]++;
cols[j][index]++;
subboxes[i/3][j/3][index]++;if(rows[i][index]>1|| cols[j][index]>1|| subboxes[i /3][j /3][index]>1){returnfalse;}}}}returntrue;}}
54.螺旋矩阵
classSolution{publicList<Integer>spiralOrder(int[][] matrix){int length = matrix[0].length;int height = matrix.length;int step =0;ArrayList<Integer> res =newArrayList<>();while(res.size()<length*height){process(step++,res, matrix);}return res;}publicvoidprocess(int step,ArrayList<Integer> res,int[][] matrix){int length = matrix[0].length;int height = matrix.length;int top = step;int right = length - step -1;int left = step;int bottom = height - top -1;for(int i = left; i <= right && res.size()< length*height; i++){
res.add(matrix[top][i]);}for(int i = top +1; i <= bottom && res.size()< length * height; i++){
res.add(matrix[i][right]);}for(int i = right-1; i >=left && res.size()< length * height; i--){
res.add(matrix[bottom][i]);}for(int i = bottom-1; i >= top+1&& res.size()< length * height; i--){
res.add(matrix[i][left]);}}}
48.旋转图像
classSolution{publicvoidrotate(int[][] matrix){int hight = matrix.length;for(int i =0; i < hight/2; i++){for(int j =0; j < matrix[0].length; j++){int t = matrix[i][j];
matrix[i][j]= matrix[hight-i -1][j];
matrix[hight-i -1][j]= t;}}for(int i =1; i < matrix.length; i++){for(int j =0; j < i; j++){int t = matrix[i][j];
matrix[i][j]=matrix[j][i];
matrix[j][i]= t;}}}}
73.矩阵置零
classSolution{publicvoidsetZeroes(int[][] matrix){boolean firstRow =false;boolean firstCol =false;for(int i =0; i < matrix[0].length; i++){if(matrix[0][i]==0) firstRow =true;}for(int i =0; i < matrix.length; i++){if(matrix[i][0]==0) firstCol =true;}for(int i =1; i < matrix.length; i++){for(int j =1; j < matrix[0].length; j++){if(matrix[i][j]==0){
matrix[0][j]=0;
matrix[i][0]=0;}}}for(int i =1; i < matrix.length; i++){for(int j =1; j < matrix[0].length; j++){if(matrix[0][j]==0||matrix[i][0]==0){
matrix[i][j]=0;}}}if(firstRow){for(int i =0; i < matrix[0].length; i++){
matrix[0][i]=0;}}if(firstCol){for(int i =0; i < matrix.length; i++){
matrix[i][0]=0;}}}}
289.生命游戏
classSolution{publicvoidgameOfLife(int[][] board){int[] neighbors ={0,1,-1};int rows = board.length;int cols = board[0].length;// 遍历面板每一个格子里的细胞for(int row =0; row < rows; row++){for(int col =0; col < cols; col++){// 对于每一个细胞统计其八个相邻位置里的活细胞数量int liveNeighbors =0;for(int i =0; i <3; i++){for(int j =0; j <3; j++){if(!(neighbors[i]==0&& neighbors[j]==0)){// 相邻位置的坐标int r =(row + neighbors[i]);int c =(col + neighbors[j]);// 查看相邻的细胞是否是活细胞if((r < rows && r >=0)&&(c < cols && c >=0)&&(Math.abs(board[r][c])==1)){
liveNeighbors +=1;}}}}// 规则 1 或规则 3 if((board[row][col]==1)&&(liveNeighbors <2|| liveNeighbors >3)){// -1 代表这个细胞过去是活的现在死了
board[row][col]=-1;}// 规则 4if(board[row][col]==0&& liveNeighbors ==3){// 2 代表这个细胞过去是死的现在活了
board[row][col]=2;}}}// 遍历 board 得到一次更新后的状态for(int row =0; row < rows; row++){for(int col =0; col < cols; col++){if(board[row][col]>0){
board[row][col]=1;}else{
board[row][col]=0;}}}}}
classSolution{publicList<String>summaryRanges(int[] nums){List<String> ret =newArrayList<String>();int i =0;int n = nums.length;while(i < n){int low = i;
i++;while(i < n && nums[i]== nums[i -1]+1){
i++;}int high = i -1;StringBuffer temp =newStringBuffer(Integer.toString(nums[low]));if(low < high){
temp.append("->");
temp.append(Integer.toString(nums[high]));}
ret.add(temp.toString());}return ret;}}
作者:力扣官方题解
链接:https://leetcode.cn/problems/summary-ranges/solutions/553645/hui-zong-qu-jian-by-leetcode-solution-6zrs/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
56.合并区间
classSolution{publicint[][]merge(int[][] intervals){Arrays.sort(intervals,Comparator.comparingInt(o -> o[0]));List<int[]> list =newArrayList<>();for(int i =0; i < intervals.length; i++){if(i< intervals.length-1&& intervals[i][1]>=intervals[i+1][0]){
intervals[i+1][1]=Math.max(intervals[i][1],intervals[i+1][1]);
intervals[i+1][0]= intervals[i][0];}else{
list.add(intervals[i]);}}return list.toArray(newint[0][]);}}
57.插入区间
classSolution{publicint[][]insert(int[][] intervals,int[] newInterval){List<int[]> ansList =newArrayList<>();int left = newInterval[0];int right = newInterval[1];boolean placed =false;for(int[] interval: intervals){if(interval[0]>right){if(!placed){
ansList.add(newint[]{left,right});
placed =true;}
ansList.add(interval);}elseif(interval[1]<left){
ansList.add(interval);}else{
left =Math.min(interval[0],left);
right =Math.max(interval[1],right);}}if(!placed){
ansList.add(newint[]{left,right});}int[][] ans =newint[ansList.size()][2];for(int i =0; i < ansList.size();++i){
ans[i]= ansList.get(i);}return ans;}}