Leetcode 523~530题

第五百二十三题:

class Solution {
public:
    bool checkSubarraySum(vector<int>& nums, int k) {
        if (!k) {
            for (int i = 1; i < nums.size(); i ++ )
                if (!nums[i - 1] && !nums[i])
                    return true;
            return false;
        }
        int n = nums.size();
        vector<int> s(n + 1);
        for (int i = 1; i <= n; i ++ ) s[i] = s[i - 1] + nums[i - 1];
        unordered_set<int> hash;
        for (int i = 2; i <= n; i ++ ) {
            hash.insert(s[i - 2] % k);
            if (hash.count(s[i] % k)) return true;
        }
        return false;
    }
};
import java.util.HashMap;
import java.util.Map;

public class Solution {

    public boolean checkSubarraySum(int[] nums, int k) {
        int sum = 0;

        // key:区间 [0..i] 里所有元素的和 % k
        // value:下标 i
        Map<Integer, Integer> map = new HashMap<>();
        // 理解初始化的意义
        map.put(0, -1);
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            sum += nums[i];
            if (k != 0) {
                sum = sum % k;
            }
            
            if (map.containsKey(sum)) {
                if (i - map.get(sum) > 1) {
                    return true;
                }
            } else {
                map.put(sum, i);
            }

        }
        return false;
    }
}
class Solution:
    def checkSubarraySum(self, nums: List[int], k: int) -> bool:
        if len(nums) < 2: return False
        dp, cur = {0: -1}, 0
        for idx, num in enumerate(nums):
            cur += num
            if k != 0: cur %= k
            pre = dp.setdefault(cur, idx)
            if idx - pre > 1: return True
        return False
func checkSubarraySum(nums []int, k int) bool {
    if len(nums) < 2 {
        return false
    }
    for i := 0; i < len(nums) - 1; i++ {
        if nums[i] == 0 && nums[i+1] == 0 {
            return true
        }
    }

    if k == 0 {
        return false
    }

    m := make(map[int]int)
    m[0] = -1 // 对于从头开始的数组,索引认为是-1,这样1--1=2
    sum, h := 0, 0
    for i := 0; i < len(nums); i++ {
        sum += nums[i]
        h = sum % k

        pre, ok := m[h]
        if !ok {
            m[h] = i
        } else {
            if i - pre > 1 {
                return true
            }
        }
    }

    return false
}

第五百二十四题:

class Solution {
public:
    bool check(string& a, string& b) {
        int i = 0, j = 0;
        while (i < a.size() && j < b.size()) {
            if (a[i] == b[j]) i ++ ;
            j ++ ;
        }
        return i == a.size();
    }

    string findLongestWord(string s, vector<string>& d) {
        string res;
        for (auto str: d)
            if (check(str, s)) {
                if (res.empty() || res.size() < str.size() || res.size() == str.size() && res > str)
                    res = str;
            }
        return res;
    }
};
public class Solution {
    public boolean isSubsequence(String x, String y) {
        int j = 0;
        for (int i = 0; i < y.length() && j < x.length(); i++)
            if (x.charAt(j) == y.charAt(i))
                j++;
        return j == x.length();
    }
    public String findLongestWord(String s, List < String > d) {
        Collections.sort(d, new Comparator < String > () {
            public int compare(String s1, String s2) {
                return s2.length() != s1.length() ? s2.length() - s1.length() : s1.compareTo(s2);
            }
        });
        for (String str: d) {
            if (isSubsequence(str, s))
                return str;
        }
        return "";
    }
}
class Solution:
    def findLongestWord(self, s: str, d: List[str]) -> str:
        
        '''
        l = 0
        longestword = []
        a = 0
        b = 0
        for word in d:
            a

            if set(word).issubset(set(s)) and len(word) >= l:
                if len(word) == l:
                    longestword = sorted([word,longestword])[0]
                else:
                    longestword = word
                l = len(word)
        return longestword
        '''
        # pythonic
        d.sort(key = lambda x: [-len(x), x])  #key  = [-len(x), x] x指传入的参数
        def f(c):
            i = 0
            for letter in c:
                k = s.find(letter, i)
                if k == -1:
                    return False
                i = k + 1
            return True
        
        for c in d:
            if f(c):
                return c 
        return ''

        #双指针
        d.sort(key = lambda x: [-len(x), x])
        for word in d:
            a = 0
            b = 0
            while a < len(s) and b < len(word):
                if s[a] == word[b]:
                    a += 1
                    b += 1
                else:
                    a += 1
            if len(word) == b:
                return word
        return ''
func findLongestWord(s string, d []string) string {
	r := ""
	if len(s) <= 0 {
		return r
	}
	for i := range d {
		if subString(s, d[i]) {
			if len(d[i]) > len(r) || (len(d[i]) == len(r) && d[i] < r )  {
				r = d[i]
			}
		}
	}
	return r
}

// 此解法也可以做判断子序列的解法
// https://leetcode-cn.com/problems/is-subsequence/ easy
func subString(s string, sub string) bool {
	if len(sub) <= 0 {
		return true
	}
	p1 := 0
	p2 := 0
	for p1 < len(s) {
		if s[p1] == sub[p2] {
			p1++
			p2++
		} else {
			p1++
		}
		if p2 == len(sub) {
			return true
		}
	}
	return false
}

第五百二十五题:

class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        int n = nums.size();
        unordered_map<int, int> hash;
        hash[0] = 0;
        int res = 0;
        for (int i = 1, one = 0, zero = 0; i <= n; i ++ ) {
            int x = nums[i - 1];
            if (x == 0) zero ++ ;
            else one ++ ;
            int s = one - zero;
            if (hash.count(s)) res = max(res, i - hash[s]);
            else hash[s] = i;
        }
        return res;
    }
};
public class Solution {

    public int findMaxLength(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        int maxlen = 0, count = 0;
        for (int i = 0; i < nums.length; i++) {
            count = count + (nums[i] == 1 ? 1 : -1);
            if (map.containsKey(count)) {
                maxlen = Math.max(maxlen, i - map.get(count));
            } else {
                map.put(count, i);
            }
        }
        return maxlen;
    }
}
class Solution:
    def findMaxLength(self, nums: List[int]) -> int:
        dic = {0:-1}
        count = res = 0
        for i in range(len(nums)):
            if nums[i] == 0:
                count -= 1
            else:
                count += 1
            if count in dic:
                res = max(i-dic[count], res)
            else:
                dic[count] = i
        return res
func findMaxLength(nums []int) int {
    cntIdx := map[int]int{
        0: -1,
    }

    cnt, maxLen := 0, 0
    for i := 0; i < len(nums); i++ {
        if nums[i] == 0 {
            cnt += -1
        } else {
            cnt += 1
        }
        if v, ok := cntIdx[cnt]; ok {
            maxLen = max(maxLen, i - v)
        } else {
            cntIdx[cnt] = i
        }
    }

    return maxLen
}

func max(a, b int) int {
    if a < b {
        return b
    }
    return a
}

第五百二十六题:

class Solution {
public:
    int countArrangement(int n) {
        vector<int> f(1 << n);
        f[0] = 1;
        for (int i = 0; i < 1 << n; i ++ ) {
            int k = 0;
            for (int j = 0; j < n; j ++ )
                if (i >> j & 1)
                    k ++ ;
            for (int j = 0; j < n; j ++ )
                if (!(i >> j & 1)) {
                    if ((k + 1) % (j + 1) == 0 || (j + 1) % (k + 1) == 0)
                        f[i | (1 << j)] += f[i];
                }
        }
        return f[(1 << n) - 1];
    }
};
public class Solution {
    int count = 0;
    public int countArrangement(int N) {
        boolean[] visited = new boolean[N + 1];
        calculate(N, 1, visited);
        return count;
    }
    public void calculate(int N, int pos, boolean[] visited) {
        if (pos > N)
            count++;
        for (int i = 1; i <= N; i++) {
            if (!visited[i] && (pos % i == 0 || i % pos == 0)) {
                visited[i] = true;
                calculate(N, pos + 1, visited);
                visited[i] = false;
            }
        }
    }
}
class Solution:
    def countArrangement(self, N: int) -> int:
        self.ans = 0
        visited = [0] * (N + 1)
        def backtrack(path):
            if len(path) == N:
                self.ans += 1
                return
            for i in range(1, N + 1):
                if visited[i]: continue
                if (len(path) + 1) % i != 0 and i % (len(path) + 1) != 0: continue 
                path.append(i)
                visited[i] = 1
                backtrack(path)
                visited[i] = 0
                path.pop()
        backtrack([])
        return self.ans
func countArrangement(N int) int {
    var ans int
    var backtrace func([]int,[]bool)

    backtrace = func(path []int,vis []bool){
        if len(path) == N {
            ans++
            return 
        }
        for v:=1;v<=N;v++ {
            if i:=len(path); vis[v-1] || v %(i+1)!=0 && (i+1)%v !=0 {
                continue
            }
            vis[v-1] = true
            backtrace(append(path, v),vis)
            vis[v-1] = false
        }
    }

    backtrace([]int{},make([]bool,N))
    return ans
}

第五百二十八题:

class Solution {
public:
    vector<int> s;

    Solution(vector<int>& w) {
        s = w;
        for (int i = 1; i < s.size(); i ++ ) s[i] += s[i - 1];
    }

    int pickIndex() {
        int x = rand() % s.back() + 1;
        return lower_bound(s.begin(), s.end(), x) - s.begin();
    }
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(w);
 * int param_1 = obj->pickIndex();
 */
class Solution {

    List<Integer> psum = new ArrayList<>();
    int tot = 0;
    Random rand = new Random();

    public Solution(int[] w) {
        for (int x : w) {
            tot += x;
            psum.add(tot);
        }
    }

    public int pickIndex() {
        int targ = rand.nextInt(tot);

        int lo = 0;
        int hi = psum.size() - 1;
        while (lo != hi) {
            int mid = (lo + hi) / 2;
            if (targ >= psum.get(mid)) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }
}
import random
class Solution:

    def __init__(self, w: List[int]):
        self.w = w
        self.leng = [0]*(len(w)+1)
        for i in range(1,len(self.leng)):
            self.leng[i] = self.leng[i-1] + self.w[i-1]


    def pickIndex(self) -> int:
        d = random.randint(1,self.leng[-1])
        l = 1;r = len(self.leng)-1
        while l <= r:
            mid = (l+r)>>1
            if self.leng[mid] >= d:
                r = mid - 1
            else:
                l = mid + 1
        index = l - 1
        return index



# Your Solution object will be instantiated and called as such:
# obj = Solution(w)
# param_1 = obj.pickIndex()
type Solution struct {
    nums []int
    sum int
}   


func Constructor(w []int) Solution {
    sum := 0
	weightSums := make([]int, len(w))
	for i := 0; i < len(w); i++ {
		sum += w[i]
		weightSums[i] = sum
	}
    return Solution{weightSums, sum}
}


func (this *Solution) PickIndex() int {
	target := rand.Intn(this.sum)
	left, right := 0, len(this.nums)
	for left < right {
		mid := left + (right - left)/2
		if target >= this.nums[mid] {
			left = mid + 1
		} else if target < this.nums[mid] {
			right = mid
		}
	}
	return left
}

第五百二十九题:

class Solution {
public:
    int n, m;

    vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
        n = board.size(), m = board[0].size();
        int x = click[0], y = click[1];
        if (board[x][y] == 'M') {
            board[x][y] = 'X';
            return board;
        }
        dfs(board, x, y);
        return board;
    }

    void dfs(vector<vector<char>>& board, int x, int y) {
        if (board[x][y] != 'E') return;
        int s = 0;
        for (int i = max(x - 1, 0); i <= min(n - 1, x + 1); i ++ )
            for (int j = max(y - 1, 0); j <= min(m - 1, y + 1); j ++ )
                if (i != x || j != y)
                    if (board[i][j] == 'M' || board[i][j] == 'X')
                        s ++ ;
        if (s) {
            board[x][y] = '0' + s;
            return;
        }
        board[x][y] = 'B';
        for (int i = max(x - 1, 0); i <= min(n - 1, x + 1); i ++ )
            for (int j = max(y - 1, 0); j <= min(m - 1, y + 1); j ++ )
                if (i != x || j != y)
                    dfs(board, i, j);
    }
};
class Solution {
    int[] dirX = {0, 1, 0, -1, 1, 1, -1, -1};
    int[] dirY = {1, 0, -1, 0, 1, -1, 1, -1};

    public char[][] updateBoard(char[][] board, int[] click) {
        int x = click[0], y = click[1];
        if (board[x][y] == 'M') {
            // 规则 1
            board[x][y] = 'X';
        } else{
            bfs(board, x, y);
        }
        return board;
    }

    public void bfs(char[][] board, int sx, int sy) {
        Queue<int[]> queue = new LinkedList<int[]>();
        boolean[][] vis = new boolean[board.length][board[0].length];
        queue.offer(new int[]{sx, sy});
        vis[sx][sy] = true;
        while (!queue.isEmpty()) {
            int[] pos = queue.poll();
            int cnt = 0, x = pos[0], y = pos[1];
            for (int i = 0; i < 8; ++i) {
                int tx = x + dirX[i];
                int ty = y + dirY[i];
                if (tx < 0 || tx >= board.length || ty < 0 || ty >= board[0].length) {
                    continue;
                }
                // 不用判断 M,因为如果有 M 的话游戏已经结束了
                if (board[tx][ty] == 'M') {
                    ++cnt;
                }
            }
            if (cnt > 0) {
                // 规则 3
                board[x][y] = (char) (cnt + '0');
            } else {
                // 规则 2
                board[x][y] = 'B';
                for (int i = 0; i < 8; ++i) {
                    int tx = x + dirX[i];
                    int ty = y + dirY[i];
                    // 这里不需要在存在 B 的时候继续扩展,因为 B 之前被点击的时候已经被扩展过了
                    if (tx < 0 || tx >= board.length || ty < 0 || ty >= board[0].length || board[tx][ty] != 'E' || vis[tx][ty]) {
                        continue;
                    }
                    queue.offer(new int[]{tx, ty});
                    vis[tx][ty] = true;
                }
            }
        }
    }
}
class Solution:
        def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
            direction = ((1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, 1), (-1, -1), (1, -1))
            if board[click[0]][click[1]] == 'M':
                board[click[0]][click[1]] = 'X'
                return board
            self.m,self.n = len(board), len(board[0])
            def check(i, j):
                cnt = 0
                for x,y in direction:
                    x, y = x + i, y + j
                    if 0 <= x < self.m and 0 <= y < self.n and board[x][y]=='M':
                        cnt += 1
                return cnt    
            def dfs(i, j):
                cnt = check(i, j)
                if not cnt:
                    board[i][j] = 'B'
                    for x, y in direction:
                        x, y = x + i, y + j
                        if  0 <= x < self.m and 0 <= y < self.n and board[x][y]=='E': dfs(x, y)
                else: board[i][j] = str(cnt)
            dfs(click[0],click[1])
            return board
var dirX = []int{0, 1, 0, -1, 1, 1, -1, -1}
var dirY = []int{1, 0, -1, 0, 1, -1, 1, -1}

func updateBoard(board [][]byte, click []int) [][]byte {
    x, y := click[0], click[1]
    if board[x][y] == 'M' {
        board[x][y] = 'X'
    } else {
        bfs(board, x, y)
    }
    return board
}

func bfs(board [][]byte, sx, sy int) {
    queue := [][]int{}
    vis := make([][]bool, len(board))
    for i := 0; i < len(vis); i++ {
        vis[i] = make([]bool, len(board[0]))
    }
    queue = append(queue, []int{sx, sy})
    vis[sx][sy] = true
    for i := 0; i < len(queue); i++ {
        cnt, x, y := 0, queue[i][0], queue[i][1]
        for i := 0; i < 8; i++ {
        tx, ty := x + dirX[i], y + dirY[i]
            if tx < 0 || tx >= len(board) || ty < 0 || ty >= len(board[0]) {
                continue
            }
            // 不用判断 M,因为如果有 M 的话游戏已经结束了
            if board[tx][ty] == 'M' {
                cnt++
            }
        }
        if cnt > 0 {
            board[x][y] = byte(cnt + '0')
        } else {
            board[x][y] = 'B'
            for i := 0; i < 8; i++ {
                tx, ty := x + dirX[i], y + dirY[i]
                // 这里不需要在存在 B 的时候继续扩展,因为 B 之前被点击的时候已经被扩展过了
                if tx < 0 || tx >= len(board) || ty < 0 || ty >= len(board[0]) || board[tx][ty] != 'E' || vis[tx][ty] {
                    continue
                }
                queue = append(queue, []int{tx, ty})
                vis[tx][ty] = true
            }
        }
    }
}

第五百三十题:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int ans = INT_MAX, last;
    bool is_first = true;

    int getMinimumDifference(TreeNode* root) {
        dfs(root);
        return ans;
    }

    void dfs(TreeNode* root) {
        if (!root) return;
        dfs(root->left);
        if (is_first) is_first = false;
        else ans = min(ans, root->val - last);
        last = root->val;
        dfs(root->right);
    }
};
class Solution {
    int pre;
    int ans;

    public int getMinimumDifference(TreeNode root) {
        ans = Integer.MAX_VALUE;
        pre = -1;
        dfs(root);
        return ans;
    }

    public void dfs(TreeNode root) {
        if (root == null) {
            return;
        }
        dfs(root.left);
        if (pre == -1) {
            pre = root.val;
        } else {
            ans = Math.min(ans, root.val - pre);
            pre = root.val;
        }
        dfs(root.right);
    }
}
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def getMinimumDifference(self, root: TreeNode) -> int:
        #初始化,最小值赋值为无穷大,last_value记录上一个节点的值
        min_value, last_value = float("inf"), -1
        def pengding_num(val):
            nonlocal min_value, last_value
            #第一个节点赋值给last_value
            if last_value == -1:
                last_value = val
            else:
                #每次求差的绝对值的最小值,更新
                min_value = min(min_value, abs(val - last_value))
                last_value = val
        #中序遍历
        def mid_order(root):
            nonlocal min_value, last_value
            if root:
                mid_order(root.left)
                #处理当前节点
                pengding_num(root.val)
                mid_order(root.right)
        mid_order(root)
        return min_value
func getMinimumDifference(root *TreeNode) int {
    ans, pre := math.MaxInt64, -1
    var dfs func(*TreeNode)
    dfs = func(node *TreeNode) {
        if node == nil {
            return
        }
        dfs(node.Left)
        if pre != -1 && node.Val-pre < ans {
            ans = node.Val - pre
        }
        pre = node.Val
        dfs(node.Right)
    }
    dfs(root)
    return ans
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不能say的秘密

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值