leetcode面试150代码保存

系列博客目录



26

/**
 * ClassName: Q3
 * Package: PACKAGE_NAME
 * Description:
 *
 * @Author 醒了就刷牙
 * @Create 2024/11/27 21:21
 * @Version 1.0
 */
public class Q3 {
    public static void main(String[] args) {

        Solution solution = new Solution();
        int[] nums1 = {1,1,2};
        solution.removeDuplicates(nums1);
    }
}
class Solution {
    public int removeDuplicates(int[] nums) {
        int index = 0;
        for (int i = 1; i < nums.length; i++) {

            if(nums[i]==nums[i-1]){
                index++;

            }
            nums[i-index] = nums[i];

        }
        return nums.length-index;
    }
}

27

import java.util.Arrays;

/**
 * ClassName: ${NAME}
 * Package:
 * Description:
 *
 * @Author 醒了就刷牙
 * @Create 2024/11/26 9:29
 * @Version 1.0
 */
public class Main {
    public static void main(String[] args) {

    Solution2 solution = new Solution2();
    int[] nums1 = {3,2,2,3};
        solution.removeElement(nums1,3);
    }
}
class Solution2 {
    public int removeElement(int[] nums, int val) {

        int index = 0 ;
//        int[] log = new int[nums.length];
//        Arrays.fill(log,0);
        for (int i = 0; i < nums.length; i++) {
            if(nums[i] == val){
                index ++;
            }else {
//                log[i]= index;
                nums[i-index]=nums[i];
            }

        }

        return nums.length-index;
    }
}

80

class Solution {
    public int removeDuplicates(int[] nums) {
        int index = 0;
        int index_double =0;
        for (int i = 1; i < nums.length; i++) {
            if(nums[i]==nums[i-1]){
                index_double ++;
                if(index_double>=2){
                    index++;
                }
            }
            else {
                index_double =0;
            }
            
            nums[i-index] = nums[i];
        }
        return nums.length-index;
    }
}

169

import java.util.Arrays;
import java.util.HashMap;

/**
 * ClassName: ${NAME}
 * Package:
 * Description:
 *
 * @Author 醒了就刷牙
 * @Create 2024/11/26 9:29
 * @Version 1.0
 */
public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums1 = {3,2,2,3};
        solution.removeDuplicates(nums1);
        System.out.println(5/2);
    }
}
class Solution {
    public int majorityElement(int[] nums) {
        HashMap<Integer, Integer> numberCount = new HashMap<>();
        for(int num:nums){
            numberCount.put(num,numberCount.getOrDefault(num,0) + 1);
        }
        // 使用 keySet() 遍历
        for (Integer key : numberCount.keySet()) {
            Integer number = numberCount.get(key);
            if(number> nums.length/2){
                return key;
            }
        }
        return 1;

    }
}

189

import java.util.Arrays;
import java.util.HashMap;

/**
 * ClassName: ${NAME}
 * Package:
 * Description:
 *
 * @Author 醒了就刷牙
 * @Create 2024/11/26 9:29
 * @Version 1.0
 */
public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums1 = {3,2,2,3};
        solution.removeDuplicates(nums1);
        System.out.println(5/2);
    }
}
class Solution {
    public void rotate(int[] nums, int k) {
        int[] result = new int[nums.length];
        int index=k%nums.length;
        for (int i = index; i < result.length; i++) {
            result[i] = nums[i-index];
        }
        for (int i = 0; i < index; i++) {
            result[i] = nums[nums.length-index+i];
        }
        for (int i = 0; i < nums.length; i++) {
            nums[i] = result[i];
        }


    }
}

121

class Solution {
    public int maxProfit(int[] prices) {
        int highest = 0;
        int low = prices[0];
        for (int i = 0; i < prices.length; i++) {
            if(low > prices[i]){
                low = prices[i];
            }
            if(prices[i]-low > highest){
                highest = prices[i] - low;
            }
        }
        return  highest;
    }
}

122

class Solution {
    public int maxProfit(int[] prices) {
        int sum = 0;
        for (int i = 1; i < prices.length; i++) {
            sum+= Math.max(prices[i] - prices[i - 1], 0);
        }
        return sum;
    }
}

55

import java.util.Arrays;
import java.util.HashMap;

/**
 * ClassName: ${NAME}
 * Package:
 * Description:
 *
 * @Author 醒了就刷牙
 * @Create 2024/11/26 9:29
 * @Version 1.0
 */
public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums1 = {0,1};
        solution.canJump(nums1);

    }
}
class Solution {
    public boolean canJump(int[] nums) {

        if(nums.length == 1){//不能忘记先判断特殊值
            return true;
        }
        if(nums[0]==0){
            return false;
        }

        int index = 0;
        int m = 0;
        int result = 0;
        for ( int i=0;i < nums.length - 1; i++) {
            if(nums[i] == 0){
                index = i;
                m = 1;
                while(index>0){
                    index--;
                    m++;
                    if(nums[index]>=m){
                        break;
                    }
                    if(index == 0){
                        return false;
                    }
                }

            }
            result ++;
        }
        return nums.length -1   == result;
    }
}

45

import java.util.Arrays;
import java.util.HashMap;

/**
 * ClassName: ${NAME}
 * Package:
 * Description:
 *
 * @Author 醒了就刷牙
 * @Create 2024/11/26 9:29
 * @Version 1.0
 */
public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums1 = {0,1};
        solution.canJump(nums1);

    }
}
class Solution {
    public int jump(int[] nums) {
        int step = 0;
        int index = 0;
        while(index < nums.length-1){ //如果数组中只有一个数字,那么结果step=0
            step++;
            int max = 0;
            int next = 0;
            int jumpLength = nums[index];
            for(int i = jumpLength;i>0;i--){
                if(i+index>=nums.length-1) return step;
                if(i +nums[index +i]>max){
                    max = nums[index + i] + i;
                    next = i+index;
                }

            }
            index = next;
        }
        return step;
    }
}

274

虽然引用数和论文数都要考虑,但是要找一个作为基准,来随着基准的增加来寻找是否有符合的H指数,下面代码用的是以论文数字为基准,出现大于论文数的引用数,才生成一个新的H指数。

class Solution {
    public int hIndex(int[] citations) {
        Arrays.sort(citations);
        int highest = 0;
        int num_paper =0;
        for (int i = citations.length-1; i >= 0; i--) {
            num_paper = citations.length-i;
            if(citations[i]>=num_paper){
                highest = num_paper;
            }
        }
        return highest;
    }
}

380

需要想到此题要用HashMap来解决

import java.util.*;

/**
 * ClassName: ${NAME}
 * Package:
 * Description:
 *
 * @Author 醒了就刷牙
 * @Create 2024/11/26 9:29
 * @Version 1.0
 */
public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums1 = {0,1};
        solution.canJump(nums1);

    }
}
class RandomizedSet {
    Map<Integer, Integer> map = new HashMap<>();
    public RandomizedSet() {
        return;
    }

    public boolean insert(int val) {
        if (map.containsKey(val)) {
            return false;
        }
        map.put(val,val);
        return true;
    }

    public boolean remove(int val) {
        if (map.containsKey(val)) {
            map.remove(val);
            return true;
        }
        return false;
    }

    public int getRandom() {
        List<Integer> values = new ArrayList<>(map.values());
        Random random = new Random();
        int randomIndex = random.nextInt(values.size());
        return values.get(randomIndex);
    }
}

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet obj = new RandomizedSet();
 * boolean param_1 = obj.insert(val);
 * boolean param_2 = obj.remove(val);
 * int param_3 = obj.getRandom();
 */

238

import java.util.*;

/**
 * ClassName: ${NAME}
 * Package:
 * Description:
 *
 * @Author 醒了就刷牙
 * @Create 2024/11/26 9:29
 * @Version 1.0
 */
public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums1 = {-1,1,0,-3,3};
        solution.productExceptSelf(nums1);

    }
}
class Solution {
    public int[] productExceptSelf(int[] nums) {
        int sum = 1;
        int zero_number =0;
        int indexOfzero = 0;
        for (int i = 0; i < nums.length; i++) {
            if(nums[i]==0 && zero_number==0){
                zero_number++;
                indexOfzero = i;
            } else if (nums[i]==0){
                zero_number++;
                sum = sum;
            }
            else {
                sum = sum * nums[i];
            }


        }
        int[] answer = new int[nums.length];
        for (int i = 0; i < answer.length; i++) {
            answer[i] = nums[i];
        }
        if(zero_number>1){
            for (int i = 0; i < answer.length; i++) {
                answer[i] = 0;
            }
        } else if (zero_number == 1) {
            for (int i = 0; i < answer.length; i++) {
                if(answer[i]==0){
                    answer[i] = sum;
                }else {
                    answer[i] = 0;
                }
            }

        } else {
            for (int i = 0; i < answer.length; i++) {
                answer[i] = sum/answer[i];
            }
        }
        return answer;
    }
}

134

屎山代码

import java.util.*;

/**
 * ClassName: ${NAME}
 * Package:
 * Description:
 *
 * @Author 醒了就刷牙
 * @Create 2024/11/26 9:29
 * @Version 1.0
 */
public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums1 = {1,2,3,4,5};
        int[] nums2 = {3,4,5,1,2};
        solution.canCompleteCircuit(nums1,nums2);

    }
}
class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int highest = 0;
        int index_highest = 0;
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < gas.length; i++) {
            gas[i] = gas[i] -cost[i];
            if(gas[i]>0){
                map.put(i,gas[i]);
            }
        }
        if(gas.length==1){
            if(gas[0]>=0) return 0;
            else return -1;
        }
        int index = -1;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            index_highest = entry.getKey();
            highest = entry.getValue();
            for(int i =index_highest+1;i<gas.length;i++){
                highest+=gas[i];
                if(highest<0) break;
            }
            if(highest>=0){
                for(int i =0 ;i<index_highest;i++){
                    highest+=gas[i];
                    if(highest<0) break;
                }
                if(highest>=0){
                    index = index_highest;
                    return index;
                }
            }
        }
        return index;
    }
}

13

抄的官网的思路:当前位置的元素比下个位置的元素小,就减去当前值,否则加上当前值

import java.util.*;

/**
 * ClassName: ${NAME}
 * Package:
 * Description:
 *
 * @Author 醒了就刷牙
 * @Create 2024/11/26 9:29
 * @Version 1.0
 */
public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums1 = {1,2,3,4,5};
        int[] nums2 = {3,4,5,1,2};

        solution.romanToInt("III");

    }
}
class Solution {
    public int romanToInt(String s) {
        Map<Character,Integer> symbolValues = new HashMap<>(){{
            put('I', 1);
            put('V', 5);
            put('X', 10);
            put('L', 50);
            put('C', 100);
            put('D', 500);
            put('M', 1000);
        }};
        char[] romanArray = s.toCharArray();
        int sum = 0;
        for (int i = 0; i < romanArray.length; i++) {
            if(i<romanArray.length-1 && symbolValues.get(romanArray[i])>=symbolValues.get(romanArray[i+1])){
                sum+=symbolValues.get(romanArray[i]);
            }
            else if(i<romanArray.length-1 && symbolValues.get(romanArray[i])<symbolValues.get(romanArray[i+1])){
                sum-=symbolValues.get(romanArray[i]);
            }else{
                sum+=symbolValues.get(romanArray[i]);
            }
        }
        return sum;
    }
}

12

看了官方解答,之前自己纯在硬凑,多个if进行判断。

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 < values.length; i++) {
            while(num>=values[i]){
                result.append(symbols[i]);
                num -= values[i];
            }
            if(num == 0){
                break;
            }
        }
        return result.toString();
    }

}

14

class Solution {
    public String longestCommonPrefix(String[] strs) {
        int length = strs.length;
        int index = 0;
        int is = 1;
        int shortlength =strs[0].length();
        for (int i = 0; i < length ; i++) {
           if(strs[i].length() < shortlength) shortlength = strs[i].length();

        }
        for (int i = 0; i < shortlength; i++) {
            for (int i1 = 0; i1 < length - 1; i1++) {
                if(strs[i1].charAt(index) != strs[i1+1].charAt(index)){
                    is = 0;
                }

            }
            index += is;
        }
        return  strs[0].substring(0,index);
    }
}

151

注意如果遇到给的字符串中有连续的空格split()会产生空的String。

class Solution {
    public String reverseWords(String s) {
        String[] result = s.split(" ");
        int length = result.length;
        String cache = "";
        for (int i = 0; i < length/2; i++) {
            cache = result[i];
            result[i] = result[length-1-i];
            result[length-1-i] = cache;
        }
        
        StringBuffer real_result = new StringBuffer();
        for (int i = 0; i < length; i++) {
            if(!Objects.equals(result[i], "")){
                real_result.append(result[i]);
            }
            if(i<length-1&&!Objects.equals(result[i+1], "")) real_result.append(" ");
        }
        return  real_result.toString();
    }
}

6

加了一个判断==1 就通过了。注意label一开始的赋值。

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();

    }
}

28

这里的+1好好体会,也可以不+1,前面变成<=。

class Solution {
    public int strStr(String haystack, String needle) {
        char[] haystackArray = haystack.toCharArray();
        char[] needleArrya = needle.toCharArray();
        int left =0;
        int right =0;
        int index =1;
        for (int i = 0; i < haystackArray.length -needleArrya.length + 1; i++) {//这里的+1好好体会
            index =0;
            if(haystackArray[i]==needleArrya[0]){
                index = 1;
                for (int i1 = 1; i1 < needleArrya.length; i1++) {
                    if(needleArrya[i1]!= haystackArray[i+i1]){
                        index =0;
                    }
                }
            }
            if(index==1){
                return i;
            }
        }
        return -1;
    }
}

125

class Solution {
    public boolean isPalindrome(String s) {
        String result = s.replace(" ","");
        result = result.toLowerCase();
        char[] charArray = result.toCharArray();
        char[] newArray = new char[charArray.length];
        int num = 0;
        for (int i = 0; i < charArray.length; i++) {
            if((48<=charArray[i]) && (charArray[i]<=57)){
                newArray[num++] = charArray[i];
            } else if (charArray[i]>=97 && charArray[i]<=122) {
                newArray[num++] = charArray[i];
            }
        }
        
        for (int i = 0; i < num; i++) {
            if(newArray[i]!= newArray[num-1-i]) return false;
        }
        return  true;
    }
}

15

查了一下Chatgpt,如何避免超出内存限制,增加了一句,通了

if (i > 0 && nums[i] == nums[i - 1]) {
    continue;
}
import org.w3c.dom.ls.LSException;

import java.util.*;

/**
 * ClassName: ${NAME}
 * Package:
 * Description:
 *
 * @Author 醒了就刷牙
 * @Create 2024/11/26 9:29
 * @Version 1.0
 */
public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums1 = {-1,0,1,2,-1,-4};
        int[] nums2 = {3,4,5,1,2};

        solution.threeSum(nums1);

    }
}
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        HashMap<Integer,Integer> map = new HashMap<>();
        List<List<Integer>> nestedList = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i],i);
        }
        int index_x , index_y = 0 ;
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            index_x = i;
            for (int i1 = i+1; i1 < nums.length; i1++) {
            	if (i1 > i+1 && nums[i1] == nums[i1 - 1]) { //注意 这里i1要大于i+1,比如x指向-1,y指向-1,时候,这个时候不能跳过,这是个 -1 -1 找个2 就可以作为答案
                    continue;
                }
                List<Integer> list = new ArrayList<>();
                index_y = i1;
                if(map.containsKey(-(nums[index_x]+nums[index_y])) && map.get(-(nums[index_x]+nums[index_y]))>index_y){
                    list.add(nums[index_x]);
                    list.add(nums[index_y]);
                    list.add(-(nums[index_x]+nums[index_y]));
                    nestedList.add(list);
                }
            }
        }
        Set<List<Integer>> set = new HashSet<>(nestedList);
        return new ArrayList<>(set);  // 将 Set 转回 List
    }
}

学习了官方题解

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> nestedList = new ArrayList<>();
        int target = 0;
        int third = 0;
        for (int first = 0; first < nums.length; first++) {
            if (first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            third = nums.length -1;
            target = - nums[first];
            for (int second = first+1; second < nums.length; second++) {
                if (second > first+1 && nums[second] == nums[second - 1]) {
                    continue;
                }
                while(second < third && nums[second]+nums[third]>target) third--;
                if(second == third) break;
                if(nums[second] + nums[third] == target){
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[first]);
                    list.add(nums[second]);
                    list.add(nums[third]);
                    nestedList.add(list);
                }
            }
        }
        return nestedList;  // 将 Set 转回 List
    }
}

392

注意 index<stoArray.lengthif(Objects.equals(s, "")) return true;
涉及到字符串,应该想到会不会出现空
涉及到数组,应该想到下表是否会越界。

class Solution {
    public boolean isSubsequence(String s, String t) {
        if(Objects.equals(s, "")) return true;
        char[] stoArray = s.toCharArray();
        char[] ttoArray = t.toCharArray();
        int n = stoArray.length;
        int index = 0;
        for (int i = 0; i < ttoArray.length; i++) {
            if(index<stoArray.length && stoArray[index]==ttoArray[i]){
                index++;
                n--;
            }
        }
        if(n==0) return true;
        return false;
    }
}

128

注意即使longOfSub>longest不满足也要把longOfSub置成零 还要注意测试用例数组中可能存在重复数值。

class Solution {
    public int longestConsecutive(int[] nums) {
        Arrays.sort(nums);
        HashSet<Integer> hashSet = new HashSet<>();
        for(int num:nums){
            hashSet.add(num);
        }
        int[] result = new int[hashSet.size()];
        int i =0;
        for(int num: hashSet){
            result[i++] = num;
        }
        Arrays.sort(result);
        int longest = 0;
        int longOfSub = 0;
        if(result.length == 1) return 1;
        if(result.length == 0) return 0;
        int n = 0;
        while(n < result.length){
            if(n<result.length-1&&result[n]==result[n+1]-1){
                longOfSub++;
            } else if (n>1 && result[n] == result[n-1]+1) {
                longOfSub++;
                if(longOfSub>longest){
                    longest = longOfSub;
                    longOfSub = 0;
                }else {
                    longOfSub = 0;
                }
            }else {
                longOfSub++;
                if(longOfSub>longest){
                    longest = longOfSub;
                    longOfSub = 0;
                }else {
                    longOfSub = 0;
                }
            }

            n++;
        }
        return  longest;
    }
}

56

思路是二维数组中,在第一维度进行遍历,如果后一个数组的left只要比现在的right小或相等,就更新下面的数组,如果不行,就把现在的数组存起来,忘记了 left也要更改。

class Solution {
    public int[][] merge(int[][] intervals) {
        for (int i = 0; i < intervals.length; i++) {
            for (int i1 = 1; i1 < intervals.length - i; i1++) {
                if(intervals[i1][0]<intervals[i1-1][0]){
                    int[] buffer = intervals[i1];
                    intervals[i1] = intervals[i1-1];
                    intervals[i1-1] = buffer;
                }
            }
        }
        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(new int[]{intervals[i][0], intervals[i][1]});
            }
        }
        return list.toArray(new int[0][]);
    }
}

1

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if(map.containsKey(target- nums[i])){
                res[0] = i;
                res[1] = map.get(target-nums[i]);
            }else {
                map.put(nums[i],i);
            }
        }
        return res;
    }
}

219

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if(map.containsKey(nums[i])&&(i-map.get(nums[i])<=k)){
                return true;

            }else{
                map.put(nums[i],i);
            }
        }
        return false;
    }
}

202

一开始忘记了 如何判断是否会循环起来。并且buffer^2 不是buffer*buffer

class Solution {
    public boolean isHappy(int n) {
        HashSet<Integer> hashSet = new HashSet<>();
        int sum = 0;
        while(true){
            hashSet.add(n);
            int m = n;
            while(m>9){
                int buffer = m%10;
                m = m/10;
                sum+= buffer*buffer;
            }
            sum += m*m;
            if(sum == 1) return true;
            sum = 0;
            while(n>9){
                int buffer = n%10;
                n = n/10;
                sum+= buffer*buffer;
            }
            sum+= n*n;
            n = sum;
            sum = 0;
            if(hashSet.contains(n)) return  false;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值