0077 LeetCode(力扣)解题录

本文记录了作者在LeetCode上的解题经历,涵盖多种算法问题的思路与解决方案,旨在提升编程思维和算法能力。
摘要由CSDN通过智能技术生成
771. 宝石与石头
class Solution {
    public int numJewelsInStones(String J, String S) {
      int count = 0;
      for (int i = 0; i<S.length() ; i++){
        if ( J.indexOf(S.charAt(i)) != -1 ){
          count++;
        }
      }
      return count;
        //O(n)
    }
}

1108. IP 地址无效化
class Solution {
    public String defangIPaddr(String address) {
        return address.replaceAll("\\.", "[.]");
    }
}


237. 删除链表中的节点
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
    
    }
}

182. 查找重复的电子邮箱
# Write your MySQL query statement below
select Email from Person where Email in (select Email from Person group by Email having count(Email) > 1) and Id in (select min(Id) from Person group by Email having count(Email) > 1);

595. 大的国家
# Write your MySQL query statement below
select name,population,area from World where area > 3000000 or population > 25000000;

1021. 删除最外层的括号
class Solution {
    public String removeOuterParentheses(String S) {
        Stack stack = new Stack();
        String result = "";
        int begin = 0;
        int end = 0;
        for (int i=0; i<S.length() ;i++){
            String s =  String.valueOf(S.charAt(i));  //char -> string
            if (")".equals(s)){
                stack.pop();
                if(stack.empty()){
                    end = i;
                    result += S.substring(begin+1,end);
                    begin = end + 1;
                }
            }else{
                stack.push(s);
           }
        }
        return result;
    }
}

938. 二叉搜索树的范围和
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int sum = 0;
    public int rangeSumBST(TreeNode root, int L, int R) {
        if (null != root){
            if (root.val >= L && root.val <= R){
                sum += root.val;
                rangeSumBST(root.left, L, R);
                rangeSumBST(root.right, L, R);
            }else if(root.val < L){
                rangeSumBST(root.right, L, R);
            }else if(root.val > R){
                rangeSumBST(root.left, L, R);
            }
        }
        return sum;
        
    }
}

709. 转换成小写字母
class Solution {
    public String toLowerCase(String str) {
        char[] chars = str.toCharArray();
        int d = 'a'-'A';
        for(int i=0; i < chars.length; i++){
            if ( chars[i] >= 'A' && chars[i] <= 'Z' ){
                chars[i] += d;
                
            }
        }
        
        return str.valueOf(chars);
        
    }
}

804. 唯一摩尔斯密码词
class Solution {
    private String[] morseCode = new String[]{".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
    public int uniqueMorseRepresentations(String[] words) {
        int len = words.length;
        Set<String> set = new HashSet();
        for(int i=0; i<len; i++){
            String word = words[i];
            String code = "";
            for(int j=0; j<word.length(); j++){
                code += morseCode[word.charAt(j) - 'a'];
            }
            set.add(code);
        }
        
        return set.size();
    }
}

832. 翻转图像
class Solution {
    public int[][] flipAndInvertImage(int[][] A) {
        int row = A[0].length;
        int[][] rotatedA = new int[row][row];
        for (int i=0; i<row; i++){
            int[] temp = new int[row];
            for (int j=0; j<row; j++){
                temp[j] = A[i][row - j - 1];
            }
            for (int k=0; k<row; k++){
                if(temp[k] == 0){
                   rotatedA[i][k] = 1; 
                }else{
                   rotatedA[i][k] = 0;
                }  
            }
            
        }
        
        return rotatedA;
        
    }
}

617. 合并二叉树
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if (t1 == null && t2 != null){
            return t2;
        }
        if (t1 != null && t2 == null){
            return t1;
        }
        if (t1 == null && t2 == null){
            return null;
        }
    
        TreeNode tn = new TreeNode(t1.val + t2.val);
        tn.left = mergeTrees(t1.left, t2.left);
        tn.right = mergeTrees(t1.right, t2.right);
        
        return tn;
        
    }
}

620. 有趣的电影
# Write your MySQL query statement below
select id,movie,description,rating from cinema where description !='boring' and id%2=1 order by rating desc;

461. 汉明距离
class Solution {
    public int hammingDistance(int x, int y) {
        int xor = x^y;
        String xorStr = Integer.toBinaryString(xor);
        int count = 0;
        for (int i=0; i<xorStr.length(); i++){
            if(xorStr.charAt(i) == '1')
                count++;
        }
        return count;
        
    }
}

657. 机器人能否返回原点
class Solution {
    public boolean judgeCircle(String moves) {
        int Lcount = 0;
        int Rcount = 0;
        int Ucount = 0;
        int Dcount = 0;
        int len = moves.length();
        for (int i=0; i<len; i++){
            char move = moves.charAt(i);
            if ('R' == move)
                Rcount++;
            if ('L' == move)
                Lcount++;
            if ('U' == move)
                Ucount++;
        }
        Dcount = len - Rcount - Lcount - Ucount;
        if (Lcount == Rcount && Ucount == Dcount)
            return true;
        return false;
    }
}
226. 翻转二叉树
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null){
            return null;
        }
        root.left = invertTree(root.left);
        root.right = invertTree(root.right);
        TreeNode tn = root.left;
        root.left = root.right;
        root.right = tn;
        return root; 
    }
}
1051. 高度检查器
class Solution {
    public int heightChecker(int[] heights) {
        int len = heights.length;
        int[] dest = new int[len];
        
        System.arraycopy(heights,0,dest,0,len);
        Arrays.sort(dest);
        
        int count = 0;
        for (int i=0; i<len; i++)
            if (dest[i] != heights[i])
                count++;
        return count;
    }
}
104. 二叉树的最大深度
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if (null == root)
            return 0;
        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; 
    }
}
627. 交换工资
# Write your MySQL query statement below
update salary 
    set sex=case sex
        when 'f' then 'm'
        when 'm' then 'f'
    end
;
977. 有序数组的平方
1
class Solution {
    public int[] sortedSquares(int[] A) {
        int len = A.length;
        for(int i=0; i<len; i++){
            A[i] = A[i]*A[i];    
        }
        Arrays.sort(A);
        return A;
         
    }
}
2
class Solution {
    public int[] sortedSquares(int[] A) {
        int len = A.length;
        int[] res = new int[len];
        int lowIndex = 0;
        int highIndex = len - 1;
        int resIndex = len -1;
        while(resIndex != -1){
            int highVal = A[highIndex]*A[highIndex];
            int lowVal = A[lowIndex]*A[lowIndex];
            if(highVal > lowVal){
                highIndex--;
                res[resIndex] = highVal;
            } else{
                lowIndex++;
                res[resIndex] = lowVal;
            }
            resIndex--;  
        }
        return res;
         
    }
}
942. 增减字符串匹配
class Solution {
    public int[] diStringMatch(String S) {
        int len = S.length();
        char[] chs = S.toCharArray();
        int[] A = new int[len+1];
        for (int i=0; i<len+1; i++)
            A[i] = i;
        int minIndex = 0;
        int maxIndex = len;
        int[] res = new int[len+1];
        
        for (int i=0; i<len; i++){
            if ('I' == S.charAt(i)){
                res[i] = A[minIndex];
                minIndex++;
            }else{
                res[i] = A[maxIndex];
                maxIndex--;
            }
        }
        res[len] = A[minIndex++];
        return res;
    }
}
728. 自除数
class Solution {
    public List<Integer> selfDividingNumbers(int left, int right) {
        List<Integer> res = new ArrayList();
        for (int num=left; num <= right; num++){
            List<String> numChars = Arrays.asList(String.valueOf(num).split(""));
            if(numChars.contains("0"))
                continue;
            int count = 0;
            for (String s:numChars){
                if (num%Integer.parseInt(s) == 0)
                    count++;
            }
            if (count == numChars.size())
                res.add(num);   
        }
        return res;
    }
}
2 //时间超限
class Solution {
    public List<Integer> selfDividingNumbers(int left, int right) {
        List<Integer> res = new ArrayList<Integer>();
        
        for (int num=left; num <= right; num++){
            int init = num;
            Boolean flag = true;
            while(num != 0){
                 int rest = num%10;
                 if (rest == 0 || init%rest != 0){
                     flag = false;
                     break;
                 }else
                     num = num/10;
             }
            
            if (flag)
                res.add(init);
        }
        
        return res;
    }
}

700. 二叉搜索树中的搜索
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 
1.无脑操作
class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        if (null == root)
            return null;
        if (root.val == val)
            return root;
        TreeNode left = searchBST(root.left, val);
        TreeNode right = searchBST(root.right, val);
        if (right != null && right.val == val)
            return right;
        if (left != null && left.val == val)
            return left;
        return null;     
    }
}
2.利用二叉树特点
class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        if (null == root)
            return null;
        if (root.val == val)
            return root;
        
        TreeNode tn = null;
        
        if (root.val > val)
            tn = searchBST(root.left, val);
        else if (root.val < val)
            tn = searchBST(root.right, val);
       
        return tn;     
    }
}

590. N叉树的后序遍历
1.迭代
/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    public List<Integer> postorder(Node root) {
        List<Integer> list = new ArrayList<Integer>();
        Stack<Node> stack = new Stack<Node>();
        
        stack.push(root);
        while( !stack.isEmpty()){
            Node node = stack.pop();
            if (node != null){
                if ( node.children != null){
                    for (Node n:node.children){
                        stack.push(n);
                    }
                }
                list.add(0,node.val);  //从前面添加
            }
        }

        return list;
        
    }
}
2.递归
class Solution {
    public List<Integer> postorder(Node root) {
        List<Integer> list = new ArrayList<Integer>();
        if (root == null)
            return list;
        for (Node node:root.children)
            list.addAll(postorder(node));
        list.add(root.val);
        return list;
        
    }
}
589. N叉树的前序遍历
1.
class Solution {
    public List<Integer> preorder(Node root) {
        List<Integer> list = new ArrayList<Integer>();
        if (root == null)
            return list;
        list.add(root.val);
        for (Node node:root.children)
            list.addAll(preorder(node));
        return list;
    }
}
292. Nim 游戏
//找规律,被4整除时后手就赢,所以先手赢就是取反
//执行用时 :0 ms, 在所有 Java 提交中击败了100.00%的用户
class Solution {
    public boolean canWinNim(int n) {
        return !(0 == n%4);
    }
}
852. 山脉数组的峰顶索引
//无脑操作
class Solution {
    public int peakIndexInMountainArray(int[] A) {
        int len = A.length;
        int index = 0;
        for (int i=1; i<=len-2; i++){
            if (A[i-1]<A[i] && A[i]>A[i+1]){
                index = i;
                break;
            }      
        }
        return index;
        
    }
}
//二分查找 0ms 击败了100.00%的用户
class Solution {
    public int peakIndexInMountainArray(int[] A) {
        int len = A.length;
        int low = 0;
        int high = len - 1;
        int index = 0;
        while(low < high-1){
            int middle = (low + high)/2;
            if (A[middle-1]<A[middle] && A[middle] < A[middle+1])
                low = middle;
            if (A[middle-1]>A[middle] && A[middle] > A[middle+1])
                high = middle;
            if (A[middle-1] < A[middle] && A[middle] > A[middle+1]){
                index = middle;
                break;
            }    
        }
        return index;
    }
}
241. 为运算表达式设计优先级
//参考别人
class Solution {
    public List<Integer> diffWaysToCompute(String input) {
        List<Integer> ways = new ArrayList<>();
        for(int i=0; i<input.length(); i++){
            char c = input.charAt(i);
            if(c=='+' || c=='-' || c=='*'){
                List<Integer> left = diffWaysToCompute(input.substring(0, i));
                List<Integer> right = diffWaysToCompute(input.substring(i+1));
                for(Integer l : left){
                    for(Integer r : right){
                        switch(c){
                            case '+':
                                ways.add(0,l+r);
                                break;
                            case '-':
                                ways.add(0,l-r);
                                break;
                            case '*':
                                ways.add(0,l*r);
                                break;
                        }
                    }
                }
            }
        }
        if(ways.size()==0)
            ways.add(Integer.valueOf(input));
        return ways;
    }
}
72. 编辑距离
//动态规划  表格法 空字符前缀
class Solution {
   
    public int minDistance(String word1, String word2) {
        int len1 = word1.length();
        int len2 = word2.length();
        int[][] count = new int[len1+1][len2+1];
        
        for (int i=0; i<len1+1; i++)
            count[i][0] = i;
        for (int j=0; j< len2+1 ;j++)
            count[0][j] = j;
        
        for (int i=1; i < len1 + 1; i++){
            for(int j=1; j < len2 + 1; j++){
                if (word1.charAt(i-1) == word2.charAt(j-1) )
                    count[i][j] = count[i-1][j-1];
                else
                    count[i][j] = Math.min(count[i-1][j-1],Math.min(count[i][j-1],count[i-1][j])) + 1;
            }
        }
        
        return count[len1][len2];
    }
}
1025. 除数博弈
//归纳法:奇数必输,偶数必赢
class Solution {
    public boolean divisorGame(int N) {
        return N%2==0;
    }
}
476. 数字的补数
class Solution {
    public int findComplement(int num) {
        int n = num;
        int ones = 1;
        while(n!=0){
            n = n>>1;
            ones = ones<<1;
        }
           ones -= 1;
        return ones^num;
        
    }
}

933. 最近的请求次数
class RecentCounter {
    Queue<Integer> q;
    public RecentCounter() {
        q = new LinkedList();
    }
    
    public int ping(int t) {
        q.add(t);
        while(q.peek() < t - 3000){
            q.poll();
        }
        return q.size();
    }
}

/**
 * Your RecentCounter object will be instantiated and called as such:
 * RecentCounter obj = new RecentCounter();
 * int param_1 = obj.ping(t);
 */
 287. 寻找重复数
 //法1:先排序
 //法二:占用 O(n)O(n) 空间
 class Solution {
    public int findDuplicate(int[] nums) {
        int len = nums.length;

        int[] array = new int[len];
        for (int i=0; i<len; i++){
            int index = nums[i];
            array[index] += 1; 
        }
        
        for(int j=0; j<len; j++){
            if(array[j] > 1)
                return j;
        }
        
        return 0;
        
    }
}
方法三:弗洛伊德的乌龟和兔子(循环检测

905. 按奇偶排序数组
1.
class Solution {
    public int[] sortArrayByParity(int[] A) {
        int len = A.length;
        int[] B = new int[len];
        int left = 0;
        int right = len - 1;
        for(int i = 0; i < len; i++){
            int a = A[i];
            if(0 == a%2){
                B[left] = a;
                left++;
            }
            else{
                B[right] = a;
                right--;
            }     
        }
        return B;   
    }
}
2.better
class Solution {

    public int[] sortArrayByParity(int[] A) {
        int len = A.length;
        int left = 0;
        int right = len - 1;
        while(left < right ){
            int la = A[left];
            int ra = A[right];
            if (0 != la%2 && 0 != ra%2)
                right--;
            if (0 == la%2 && 0 == ra%2)
                left++;
            if (0 != la%2 && 0 == ra%2){
                A[left] = ra;
                A[right] = la;
                right--;
                left++;
            }
            if (0 == la%2 && 0 != ra%2){
                right--;
                left++;
            }
        }
        return A;
        
    }
}
344. 反转字符串
1.双指针
class Solution {
    public void reverseString(char[] s) {
        int left = 0;
        int right = s.length - 1;
        while(left < right){
            char tmp = s[left];
            s[left] = s[right];
            s[right] = tmp;
            left++;
            right--;
        }
        System.out.println(s);
    }
}
557. 反转字符串中的单词 III
性能极差
class Solution {
    public String reverseWords(String s) {
        String[] arr = s.split(" ");
        String str = "";
        for(int i = 0; i<arr.length; i++){
            str += reverseString(arr[i].toCharArray()) + " ";
        }
        
        return str.trim();
    }
    
    public String reverseString(char[] s) {
        int left = 0;
        int right = s.length - 1;
        while(left < right){
            char tmp = s[left];
            s[left] = s[right];
            s[right] = tmp;
            left++;
            right--;
        }
        return String.valueOf(s);
    }
}
5. 最长回文子串
1、抄袭
class Solution {
    public String longestPalindrome(String s) {
     if(s == null || s.length() == 0){
            return "";
        }
		char[] chars = s.toCharArray();
		int num = chars.length - 1;
		int maxLength = 0;
		int left = 0;
		int right = 0;
		for (int i = 0; i < chars.length - maxLength; ) {
			char ch = chars[i];
			int pos = s.lastIndexOf(ch, num); //定位相同字符
			if (i == pos || pos - i < maxLength) {
				i++;
				num = chars.length - 1;
				continue;
			}
			int posRec = pos;
			pos--;
			boolean success = true;
			for (int j = i + 1; j < pos; j++, pos--) { //判断是否回文字符串
				if (chars[j] != chars[pos]) {
					success = false;
					break;
				}
			}
			if (success) {  //记
               maxLength = posRec - i;
				left = i;
				right = posRec;
			}
			num = posRec - 1;
		}
		return s.substring(left, right + 1);
        
    }
}
//中心扩展
public String longestPalindrome(String s) {
    if (s == null || s.length() < 1) return "";
    int start = 0, end = 0;
    for (int i = 0; i < s.length(); i++) {
        int len1 = expandAroundCenter(s, i, i);
        int len2 = expandAroundCenter(s, i, i + 1);
        int len = Math.max(len1, len2);
        if (len > end - start) {
            start = i - (len - 1) / 2;
            end = i + len / 2;
        }
    }
    return s.substring(start, end + 1);
}
//dp
class Solution {
    public String longestPalindrome(String s) {
        if (null == s || "".equals(s))
            return s;
        int len = s.length();
        boolean[][] dp = new boolean[len][len];
        String res = null;
        for(int i = len - 1; i >= 0; i--){
            for (int j = i; j < len; j++){
            dp[i][j] = (s.charAt(i) == s.charAt(j)) && (j-i <= 2 || dp[i+1][j-1]);
            if (dp[i][j] && (res == null || j-i+1 > res.length()))
                res = s.substring(i, j+1);
            }
        }
        return res;

private int expandAroundCenter(String s, int left, int right) {
    int L = left, R = right;
    while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
        L--;
        R++;
    }
    return R - L - 1;
}

2.
class Solution {
    public String longestPalindrome(String s) {
        if (null == s || "".equals(s))
            return s;
        int len = s.length();
        boolean[][] dp = new boolean[len][len];
        String res = null;
        for(int i = len - 1; i >= 0; i--){
            for (int j = i; j < len; j++){
            dp[i][j] = (s.charAt(i) == s.charAt(j)) && (j-i <= 2 || dp[i+1][j-1]);
            if (dp[i][j] && (res == null || j-i+1 > res.length()))
                res = s.substring(i, j+1);
            }
        }
        return res;  
        
    }
}
70. 爬楼梯
//暴力法 O(2^n) 深度n
class Solution {
    public int climbStairs(int n) {
        if (1 == n)
            return 1;
        if (2 == n)
            return 2;
        return climbStairs(n -1) + climbStairs(n - 2);
    }
}
//动态规划 T:O(n) S:O(n)
class Solution {
    public int climbStairs(int n) {
        if (1 == n)
            return 1;
        if (2 == n)
            return 2;
        int[] dp = new int[n];
        dp[0] = 1;
        dp[1] = 2;
        for (int i = 2; i<n; i++){
            dp[i] = dp[i-1] + dp[i-2];
        }
        return dp[n-1];
    }
}
//斐波那契  T:O(n) S:O(1)
class Solution {
    public int climbStairs(int n) {
        if (1 == n)
            return 1;
        if (2 == n)
            return 2;
        int first = 1;
        int second = 2;
        int Fib = 0;
        for (int i = 3; i<=n ; i++){
            Fib = first + second;
            first = second;
            second = Fib;
        }
        return Fib;
    }
}
41. 缺失的第一个正数
//hashMap  T:O(n) S:O(n)
class Solution {
    public int firstMissingPositive(int[] nums) {
        int len = nums.length;
        int res = 0;
        Map<Integer,Boolean> hm = new HashMap<>();
        for (int i = 0; i < len; i++)
            hm.put(nums[i],true);
        
        for(int j = 1; j < Integer.MAX_VALUE ; j++){
            if ( !hm.containsKey(j) ){
                 res = j;
                 break;
            }  
        }
        return res; 
    }
}
53. 最大子序和
class Solution {
    public int maxSubArray(int[] nums) {
        int len = nums.length;
        int[] dp = new int[len];
        dp[0] = nums[0];
        int max = nums[0];
        for (int i=1; i<len; i++){
            if (dp[i-1] > 0)
                dp[i] = dp[i-1] + nums[i];
            else
                dp[i] = nums[i];
            max = Math.max(max, dp[i]);
        }
        return max;
    }
}
28. 实现 strStr()
class Solution {
    public int strStr(String haystack, String needle) {
        if (null == haystack || null == needle )
            return 0;
        if (haystack.equals(needle))
            return 0;
        int n = haystack.length();
        int m = needle.length();
        if (n < m )
            return -1;
            
        int start = 0;
        int end = m;
        Boolean flag = false;
        while(end <= n){
            if ( needle.equals(haystack.substring(start, end)) ){
                flag = true;
                break; 
            }
            start++;
            end++;
        }
        if (false == flag)
            return -1;
        return start;
    }
}
234. 回文链表
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        if (null == head || null == head.next)
            return true;
        //双指针找中点
        if (head == null || head.next == null) {
            return true;
        }
        //快慢指针找到链表的中点
        ListNode fast = head.next.next;
        ListNode slow = head.next;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }

        //翻转链表前半部分
        ListNode pre = null;
        ListNode next = null;
        while (head != slow) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        //如果是奇数个节点,去掉后半部分的第一个节点。

        if (fast != null) {
            slow = slow.next;
        }
        //回文校验
        while (pre != null) {
            if (pre.val != slow.val) {
                return false;
            }
            pre = pre.next;
            slow = slow.next;
        }

        return true;

    }
}
78. 子集
//位掩码
class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        int len = nums.length;
        int n = 1 << len;
        for (int i=0; i<n; i++){
            List<Integer> list = new ArrayList<Integer>();
            for (int j=0; j<len; j++){
                if ( ((i >> j) & 1 ) == 1)
                    list.add(nums[j]);
            }
            res.add(list);
        }
        
        return res;
    }
}
//回溯法


206. 反转链表
头结点插入法,迭代
执行用时 :
0 ms, 在所有 Java 提交中击败了100.00%   36.6 MB, 在所有 Java 提交中击败了55.26%的用户

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if (null == head)
            return null;
        ListNode tmpHead = head;
        ListNode newHead = null;  //初始尾节点
        
        //从头部插入
        while (tmpHead != null){
            ListNode tmp = tmpHead.next;  //临时保存下一节点
            
            ListNode tmp1 = newHead;  //临时保存新头结点
            newHead = tmpHead;
            newHead.next = tmp1;    //头结点插入
            
            tmpHead = tmp;
        }
        
        return newHead;
    }
}
递归方法
class Solution {
    public ListNode reverseList(ListNode head) {
        if (null == head || null == head.next)
            return head;
        
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}
136. 只出现一次的数字
//最佳
class Solution {
    public int singleNumber(int[] nums) {
        int n = nums.length;
        int res = nums[0];
        for(int i = 1; i < n; i++){
            res = res ^ nums[i];  //相同元素异或值为0,不为0的那个就是只出现一次的
        }
        return res;
    }
}
//哈希表
class Solution {
    public int singleNumber(int[] nums) {
        int n = nums.length;
        HashMap<Integer,Integer> hm = new HashMap();
        for (int i=0; i < n; i++){
            int ele = nums[i];
            if (hm.containsKey(ele)){
                hm.put(ele, hm.get(ele) + 1);
            }else{
                hm.put(ele, 1);
            }  
        }
        for (int key:hm.keySet()){
            if (1 == hm.get(key))
                return key;
        }
            
        return -1;
    }
}
235. 二叉搜索树的最近公共祖先
思路:如果两个值都小于或大于当前节点,则继续寻找;若一个大于当前节点,一个小于当前节点,说明当前节点就是两点的最后一个分叉点,即最近公共祖先节点
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (null == root || null == p || null == q)
            return null;
        while (root != null){
            if ((p.val <= root.val && q.val >= root.val) 
               || (p.val >= root.val && q.val <= root.val)){
                return root;
            }else if (p.val > root.val && q.val > root.val)
                root = root.right;
            else
                root = root.left;
        }
        return null;
    }
    
}
169. 求众数
//先排序,则数组中点位置一定是数量过半的众数
class Solution {
    public int majorityElement(int[] nums) {
        int n = nums.length;
        Arrays.sort(nums);
        return nums[n/2];
    }
}
//维护一个计数器,不断更新候选众数,元素与候选众数相等计数器+1,反之-1,如果计数器=0,则舍弃前面操作,更新候选众数为当前元素
class Solution {
    public int majorityElement(int[] nums) {
        Integer target = null;
        int counter = 0;
        for (int num:nums){
            if (0 == counter)
                target = num;  //舍弃前面的操作
            
            if (target == num)
                counter++;
            else
                counter--;
        }
        return target;
    }
}
21. 合并两个有序链表
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode p = head;
        while(l1 != null && l2 != null){
           if (l1.val < l2.val){
               head.next = l1;
               l1 = l1.next;
           } else{
               head.next = l2;
               l2 = l2.next;
           } 
           head = head.next;
       }
        //当长短不一样时,最后一个节点指向还剩的那一截
        head.next = (l1==null)?l2:l1;
        return p.next;
    }
}
9. 回文数
时间复杂度 O(log10(n))
class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0 || x%10 == 0 && x != 0)
            return false;
       
        int halfX = 0;
        while(halfX < x){
            halfX = halfX*10 + x%10;
            x /= 10;
        }

        return x == halfX || x == halfX/10;
        
    }
}
122. 买卖股票的最佳时机 II
class Solution {
    public int maxProfit(int[] prices) {
        int max = 0;
        int minIndex = 0;
        for (int i = 1 ; i < prices.length; i++){
            if (prices[minIndex] < prices[i]){
                max += prices[i] - prices[minIndex];
                minIndex = i;
            }else{
                minIndex = i;
            }
        }
        return max;
    }
}
7. 整数反转
class Solution {
    public int reverse(int x) {
        int revX = 0;
        while(x != 0){
            int num = x%10;
            if (revX > Integer.MAX_VALUE/10 || (revX==Integer.MAX_VALUE/10 && num > 7)) return 0;
            if (revX < Integer.MIN_VALUE/10 || (revX==Integer.MIN_VALUE/10 && num < -8)) return 0;
            revX = revX*10 + num;
            x /= 10;
        }
        
        return revX;
    }
}
231. 2的幂
class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n < 0)
            return false;
        int countOne = 0;
        while (n != 0 ){
            if ((n & 1) == 1)
                countOne++;
            n = (n >> 1);
        }
        return (countOne==1)?true:false;
        
    }
}
也可以n & (n - 1) == 0判断,正负通用

155. 最小栈
class MinStack {

    /** initialize your data structure here. */
    private List<Integer> list = new ArrayList();
    private List<Integer> minList = new ArrayList();
    private Lock lock = new ReentrantLock();
    public MinStack() {
        
    }
    
    public void push(int x) {
        lock.lock();
        try{
        list.add(0,x);
        minList.add(x);
        Collections.sort(minList);
        }finally{
            lock.unlock();
        }
    }
    
    public void pop() {
        if (list.isEmpty())
            return;
        lock.lock();
        try{
        int top = list.get(0);
        list.remove(0);
        for (int i=0; i<minList.size(); i++){
            if (minList.get(i) == top)
                minList.remove(i);
        }
        }
        finally{
            lock.unlock();
        }
        
        return;
    }
    
    public int top() {
        if (list.isEmpty())
            return 0;
        return list.get(0);
    }
    
    public int getMin() {
        return minList.get(0);
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */
217. 存在重复元素
class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> hashSet = new HashSet();
        for (int ele:nums)
            hashSet.add(ele);
        return (nums.length==hashSet.size())?false:true;
    }
}
//不如以上
class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> hashSet = new HashSet();
        for (int ele:nums){
            if (hashSet.contains(ele))
                return true;
            hashSet.add(ele);
        }
            
        return false;
    }
}
160. 相交链表
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null)
            return null;
        ListNode pA = headA;
        ListNode pB = headB;
        while (pA != pB){
            pA = pA == null?headB:pA.next;
            pB = pB == null?headA:pB.next;
        }
        return pA;
    }
}













 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值