class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int p1 = 0;
int p2 = 0;
int[] res = new int[m+n];
int cur;
while(p1 < m || p2 < n){
if(p2 == n){
cur = nums1[p1++];
}else if (p1 == m) {
cur = nums2[p2++];
}else if (nums1[p1] < nums2[p2]){
cur = nums1[p1++];
}else {
cur = nums2[p2++];
}
res[p1 + p2 -1] = cur;
}
for (int i = 0; i < res.length; i++) {
nums1[i] = res[i];
}
}
}
class Solution {
public int removeElement(int[] nums, int val) {
int left = 0;
int right = nums.length-1;
while(left<=right){
if(nums[left] == val){
nums[left] = nums[right--];
}else {
left++;
}
}
return left;
}
}
class Solution {
public int removeDuplicates(int[] nums) {
int fast = 1;
int slow = 1;
while(fast<nums.length){
if(nums[fast]!=nums[fast-1]){
nums[slow++] = nums[fast++];
}else {
fast++;
}
}
return slow;
}
}
class Solution {
public int removeDuplicates(int[] nums) {
int fast = 2;
int slow = 2;
while(fast < nums.length){
if(nums[fast]!=nums[slow-2]){
nums[slow++] = nums[fast++];
}else {
fast++;
}
}
return slow;
}
}
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
class Solution {
public void rotate(int[] nums, int k){
k = k%nums.length;
reverse(nums,0,nums.length-1);
reverse(nums,0,k-1);
reverse(nums, k,nums.length-1);
}
public void reverse(int[] nums, int s, int e){
while(s<e){
int temp = nums[s];
nums[s] = nums[e];
nums[e] = temp;
s++;
e--;
}
}
}
class Solution {
public int maxProfit(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;
}
}
class Solution {
public int maxProfit(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;
}
}
class Solution {
public boolean canJump(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 ) return true;
if(maxIndex == 0) return false;
index = maxIndex;
}
}
}
class Solution {
public int jump(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;
}
return 0;
}
}
链接
class Solution {
public int hIndex(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;
}
}
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] L = new int[nums.length];
int[] R = new int[nums.length];
int[] answer = new int[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;
}
}
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int start = -1;
int sumgas = 0;
int mingas = 0;
int length = gas.length;
//找到耗油最多的点
for (int i = 0; i < length; i++) {
sumgas += gas[i] - cost[i];
if(sumgas<mingas){
mingas = sumgas;
start = i;
}
}
//返回开始点为油最多的点,也就是耗油最多的点后一个点。
return sumgas<0?-1:(start+1)%length;
}
}
class Solution {
public int romanToInt(String s) {
Map<Character, Integer> map = new HashMap<>();
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;
}
}
class Solution {
public String intToRoman(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 = new StringBuffer();
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();
}
}
class Solution {
public int lengthOfLastWord(String s) {
String[] result = s.split(" ");
return result[result.length - 1].length();
}
}
class Solution {
public String longestCommonPrefix(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];
}
}
class Solution {
public String reverseWords(String s) {
// 除去开头和末尾的空白字符
s = s.trim();
// 正则匹配连续的空白字符作为分隔符分割
List<String> wordList = Arrays.asList(s.split("\\s+"));
Collections.reverse(wordList);
return String.join(" ", wordList);
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/reverse-words-in-a-string/solutions/194450/fan-zhuan-zi-fu-chuan-li-de-dan-ci-by-leetcode-sol/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public String convert(String s, int numRows) {
StringBuffer buffer = new StringBuffer();
if(numRows == 1){
return s;
}
for(int j = 0; j < s.length(); j = j + (numRows-1)*2){
buffer.append(s.charAt(j));
}
for (int i = 1; i < numRows-1; i++) {
int label =1;
for(int j = i; j < s.length(); j += label==0 ? ((numRows-i-1)*2) : i*2){
buffer.append(s.charAt(j));
label = label==0 ? 1:0;
}
}
for(int j = numRows-1; j < s.length(); j = j + (numRows-1)*2){
buffer.append(s.charAt(j));
}
return buffer.toString();
}
}
class Solution {
public int strStr(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;
}
}
class Solution {
public boolean isPalindrome(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))){
return false;
}
left++;
right--;
}
}
return true;
}
}
class Solution {
public boolean isSubsequence(String s, String t) {
char[] schar = s.toCharArray();
char[] tchar = t.toCharArray();
if(schar.length == 0) return true;
int index =0;
for (int i = 0; i < tchar.length; i++) {
if(schar[index]==tchar[i]) index++;
if(index==schar.length) return true; //注意这条语句在for循环里面,要不然index会越界
}
return false;
}
}
class Solution {
public int[] twoSum(int[] numbers, int target) {
Map<Integer,Integer> hashMap = new HashMap<>();
for (int i = 0; i < numbers.length; i++) {
if(hashMap.containsKey(target - numbers[i])){
return new int[]{hashMap.get(target - numbers[i])+1,i+1};
}
hashMap.put(numbers[i],i);
}
return null;
}
}
class Solution {
public int maxArea(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;
}
}
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
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 = new ArrayList<>();
buffer.add(nums[first]);
buffer.add(nums[second]);
buffer.add(nums[third]);
res.add(buffer);
}
}
}
return res;
}
}
class Solution {
public int minSubArrayLen(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;
}
}
class Solution {
public int lengthOfLongestSubstring(String s) {
char[] chars = s.toCharArray();
HashMap<Character,Integer> hashMap = new HashMap<>();
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;
}
}
class Solution {
public boolean isValidSudoku(char[][] board) {
int[][] rows = new int[9][9];
int[][] cols = new int[9][9];
int[][][] subboxes = new int[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) {
return false;
}
}
}
}
return true;
}
}
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int length = matrix[0].length;
int height = matrix.length;
int step = 0;
ArrayList<Integer> res = new ArrayList<>();
while(res.size()<length*height){
process(step++,res, matrix);
}
return res;
}
public void process(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]);
}
}
}
class Solution {
public void rotate(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;
}
}
}
}
class Solution {
public void setZeroes(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;
}
}
}
}
class Solution {
public void gameOfLife(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;
}
// 规则 4
if (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;
}
}
}
}
}
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String,List<String>> map = new HashMap<>();
for(String str : strs){
char[] chars = str.toCharArray();
Arrays.sort(chars);
String key = new String(chars);
List<String> list = map.getOrDefault(key,new ArrayList<String>());
list.add(str);
map.put(key,list);
}
return new ArrayList<List<String>>(map.values());
}
}
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> num_set = new HashSet<Integer>();
for (int num : nums) {
num_set.add(num);
}
int longestStreak = 0;
for (int num : num_set) {
if (!num_set.contains(num - 1)) {
int currentNum = num;
int currentStreak = 1;
while (num_set.contains(currentNum + 1)) {//不要用currentNum++
currentNum += 1;
currentStreak += 1;
}
longestStreak = Math.max(longestStreak, currentStreak);
}
}
return longestStreak;
}
}
class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> ret = new ArrayList<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 = new StringBuffer(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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals,Comparator.comparingInt(o -> o[0]));
List<int[]> list = new ArrayList<>();
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(new int[0][]);
}
}
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> ansList = new ArrayList<>();
int left = newInterval[0];
int right = newInterval[1];
boolean placed = false;
for(int[] interval: intervals){
if(interval[0]>right){
if(!placed){
ansList.add(new int[]{left,right});
placed = true;
}
ansList.add(interval);
}
else if(interval[1]<left){
ansList.add(interval);
}else {
left = Math.min(interval[0],left);
right = Math.max(interval[1],right);
}
}
if(!placed){
ansList.add(new int[]{left,right});
}
int[][] ans = new int[ansList.size()][2];
for (int i = 0; i < ansList.size(); ++i) {
ans[i] = ansList.get(i);
}
return ans;
}
}