text stringlengths 129 2.29M | file_name stringlengths 3 1.88k ⌀ | file_ext stringclasses 243
values | file_size_in_byte int64 129 2.29M | lang stringclasses 85
values | program_lang stringclasses 154
values |
|---|---|---|---|---|---|
"""
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/?envType=study-plan&id=level-1
"""
class Solution:
def maxProfit(self, prices: List[int]) -> int:
sellDate = 0
holdDate = -math.inf
for price in prices:
sellDate = max(sellDate, holdDate+price)
holdDa... | 121.BestTimeToBuy&SellStock.py | py | 370 | en | python |
func maximumDifference(nums []int) int {
if len(nums) ==0{
return -1
}
min :=nums[0]
diff :=0
maxDiff :=-1
for _,n := range nums{
diff = n-min
if n<min{
min = n
}
if diff >0 && diff > maxDiff{
maxDiff = diff
}
}
ret... | maximum-difference-between-increasing-elements.go | go | 334 | en | go |
import { ObjectId, Db, Collection } from 'mongodb';
import { getCollection } from '../db/connection';
import { ExtendedError, createExtendedError } from '../errors/helpers';
import {
UserDocument,
CreateUserInDb,
addGroupInput,
addAdminInput
} from '../types/userTypes';
import { injectDb } from './helpe... | User.ts | ts | 12,793 | en | typescript |
<?php
/**
* Created by PhpStorm.
* User: chenzhe
* Date: 2019/11/19
* Time: 4:04 下午
* Desc:
*/
class Solution42
{
//按照行去计算每行有多少个需要填充的块,会超时
public function getResultByRow($num){
if(count($num) <= 2){
return 0;
}
$longest = max($num);
$res = 0;
$len = c... | test42.php | php | 3,411 | en | php |
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
public int search(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
int l = 0;
int r = nums.length - 1;
while(l<r){
int mid = (l+r)/2;
... | Solution.java | java | 4,729 | en | java |
// By Vishwam Shriram Mundada
// https://practice.geeksforgeeks.org/problems/merge-k-sorted-arrays/1#
// Decent
/*
Given K sorted arrays arranged in the form of a matrix of size K*K. The task is to merge them into one sorted array.
Example 1:
Input:
K = 3
arr[][] = {{1,2,3},{4,5,6},{7,8,9}}
Output: 1 2 3 4 5 6 7 8 9
... | Merge k Sorted Arrays.cpp | cpp | 2,047 | en | cpp |
package largest_number
import (
"sort"
"strconv"
)
func largestNumber(nums []int) string {
strNums := make([]string, 0)
for _, v := range nums {
strNums = append(strNums, strconv.Itoa(v))
}
sort.Slice(strNums, func(i, j int) bool {
return strNums[i]+strNums[j] > strNums[j]+strNums[i]
})
if strNums[0] == ... | largest_number.go | go | 410 | en | go |
# 题意:给一个node,找距离为k的nodes,返回[]
# 思路:建图 + BFS
#
# Time Complexity: O(N)
# Space Complexity: O(N)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def distanceK(self, root: TreeNode, target... | 863. All Nodes Distance K in Binary Tree.py | py | 1,585 | en | python |
#include <iostream>
#include <vector>
#include <string>
#include <climits>
class Solution {
public:
bool isPalindrome(int x) {
int reverse_num = 0;
if (x < 0) {
return false;
x = -x;
}
int x_bak = x;
while (x > 0) {
reverse_num = reverse_n... | palindorme_number.cpp | cpp | 647 | en | cpp |
/*
* [157] Read N Characters Given Read4
*
* https://leetcode.com/problems/read-n-characters-given-read4/description/
*
* algorithms
* Easy (28.41%)
* Total Accepted: 54K
* Total Submissions: 190.1K
* Testcase Example: '""\n0'
*
* The API: int read4(char *buf) reads 4 characters at a time from a file.
*... | 157.read-n-characters-given-read4.cpp | cpp | 1,363 | en | cpp |
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> ans;
int n = nums.size();
/*
First I Traverse through the array.
When i see an element x for the first time,
I’ll negate the value at... | Find-all-duplicates-in-an-array.cpp | cpp | 825 | en | cpp |
package algorithms.warmup;
import java.util.Scanner;
public class Solution1 {
static int result = 0;
static int solveMeFirst(int a, int b) {
if(a >= 1 && b >= 1 && a <= 1000 && b <= 1000){
result = a + b;
}
return result;
}
public static void main(String[] args) {
Scanne... | Solution1.java | java | 532 | en | java |
// Given a binary tree, return all root-to-leaf paths.
//
// Note: A leaf is a node with no children.
//
// Example:
//
//
// Input:
//
// 1
// / \
// 2 3
// \
// 5
//
// Output: ["1->2->5", "1->3"]
//
// Explanation: All root-to-leaf paths are: 1->2->5, 1->3
//
/**
* Definition for a binary tree node.
... | 257_Binary_Tree_Paths.java | java | 1,780 | en | java |
package Coding.Tree.BinaryTree.Convert;
// https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/
// same code will work for Binary Tree to DLL
public class ConvertSortedBSTToDLL {
Node prev = null;
Node headLinkedList = null;
public Node treeToDoublyList(Node root) {
... | ConvertSortedBSTToDLL.java | java | 1,558 | en | java |
//LeetCode - 187. Given a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order.
#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;
class Solution{
public:
vecto... | DNA.cpp | cpp | 1,152 | en | cpp |
class Solution:
@cache
def isValid(self, s: str) -> bool:
open = 0
for c in s:
if c == '(': open += 1
if c == ')':
if open: open -= 1
else: return False
return not open
def removeInvalidParentheses(self, s: str) -> List[str... | remove-invalid-parentheses.py | py | 1,071 | en | python |
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
全排列,包含重复数字
"""
if len(nums) <= 1: # 如果当前lst长度为1,停止递归,返回
return [nums]
result = []
table = []
for i in range(len(nums)):
... | Que47.py | py | 856 | en | python |
#include <algorithm>
#include <vector>
using namespace std;
// 0 ms, 8.9 MB. DP
class Solution1 {
public:
int rob(vector<int>& nums) {
if (nums.size() < 2) {
return nums.empty() ? 0 : nums[0];
}
memo_ = vector<int>(nums.size() + 1, -1);
memo_[0] = 0;
memo_[1] = nums[0];
return TryRob(n... | house_rober.cc | cc | 1,813 | en | cpp |
import java.util.LinkedList;
import java.util.List;
public class Solution216 {
public static void main(String[] args) {
Solution216_1 s = new Solution216_1();
s.combinationSum3(3,7);
}
}
class Solution216_1 {
List<List<Integer>> res = new LinkedList<>();
List<Integer> path = new Linked... | Solution216.java | java | 976 | en | java |
from collections import Counter
def solution(a, b, c, d):
numbers = Counter([a, b, c, d]).most_common()
if len(numbers) == 1:
return 1111 * numbers[0][0]
elif len(numbers) == 2:
if numbers[0][1] == 3:
return (10 * numbers[0][0] + numbers[1][0]) ** 2
else:
ret... | 주사위 게임 3.py | py | 510 | en | python |
package main
import "fmt"
func main() {
fmt.Println(matrixBlockSum([][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}, 2))
}
func matrixBlockSum(mat [][]int, k int) [][]int {
dp := make([][]int, len(mat))
for i := range dp {
dp[i] = make([]int, len(mat[i]))
}
for i := range dp {
sum := 0
for j := range dp... | main.go | go | 892 | en | go |
package methodEmbedding.Magic_Trick.S.LYD1316;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Solution {
public Solution() {
Scanner in = new Scanner(System.in);
int T = in.nextInt();
for (int i = 0; i < T; i++) {
int firstAnswer[] = new int[4];
int secondAn... | Solution(4).java | java | 1,323 | en | java |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), l... | 1116-maximum-level-sum-of-a-binary-tree.cpp | cpp | 1,134 | en | cpp |
/* Leetcode 229.求众数 II
* 给定一个大小为 n 的数组,找出其中所有出现超过 ⌊n/3⌋ 次的元素。
* 说明: 要求算法的时间复杂度为O(n),空间复杂度为O(1)。
*/
#include <vector>
using namespace std;
/* 摩尔投票法进阶版
* 首先, 一个大小为n的数组, 出现超过⌊n/m⌋的元素最多只有m-1个
* 因此这题最多只有2个元素
*
* 思路:
* 首先假设出现次数最大的两个数是A, B, 注意, 它们出现的次数不一定超过⌊n/3⌋
* 那么我们每次拿走3个不一样的数, 最后剩下来的一定是A, B, 分以下情况讨论
* (1)3个数中包含... | Majority Element 2.cpp | cpp | 2,686 | zh | cpp |
package Leetcode.OneToThousand.TwoHundredToThreeHundred;
import Leetcode.ListNode;
public class DeleteNodeInALinkedList {
public static void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
public static void main(String[] args) {
Li... | DeleteNodeInALinkedList.java | java | 852 | en | java |
/*
* @Author: your name
* @Date: 2020-09-25 10:43:05
* @LastEditTime: 2020-09-25 15:58:04
* @LastEditors: Please set LastEditors
* @Description: 106. 从中序与后序遍历序列构造二叉树
根据一棵树的中序遍历与后序遍历构造二叉树。
* @FilePath: /undefined/home/whh/programming/Leetcode/106.cpp
*/
#include "dependOn.h"
#include <map>
using std::map;
clas... | 106.cpp | cpp | 1,027 | en | cpp |
from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
i, j = 0, 0
while i < m+n and j < n:
if nums2[j] < nums1[i]:
del n... | 88_merge_sorted_array.py | py | 656 | en | python |
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies) {
vector<bool> b;
int a = *max_element(candies.begin(), candies.end());
for (int i = 0; i < candies.size(); i++)
{
if(candies[i] +... | 1431.cpp | cpp | 515 | en | cpp |
package com.geforcelee.leetcode.i75;
public class SortColors2 {
public static void sortColors(int[] nums) {
//[0,lt] 0
//[lt+1,i-1] = 1
//[gt,length-1] = 2
int lt = -1;
int gt = nums.length;
for (int i = 0; i < nums.length && gt >i; ) {
int v = nums[i];
... | SortColors2.java | java | 928 | en | java |
/*
* @lc app=leetcode.cn id=645 lang=javascript
*
* [645] 错误的集合
*/
// 找到重复的数!找到丢失的数!分两步走!不要混在一起!
// @lc code=start
/**
* @param {number[]} nums
* @return {number[]}
*/
var findErrorNums = function (nums) {
let renum = 0; lostnum = 0;
for (let i = 0; i < nums.length; i++) {
if (nums.indexOf(nums[i]) !==... | 645.错误的集合.js | js | 613 | en | javascript |
'''
You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval.... | 57_Insert_Interval.py | py | 2,020 | en | python |
import java.lang.Math;
class Solution {
public int findContentChildren(int[] g, int[] s) {
if (g.length ==0 || s.length ==0) return 0;
/*In Greedy problem we try to solve piece by piece*/
int count =0,l=0,m=0;
// here we are runing till our greeds are satisfying and once it satisy w... | 455-assign-cookies.java | java | 722 | en | java |
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
if digits[-1]<9:
digits[-1] += 1
return digits
reg = 0
for i in range(0, len(digits)):
if digits[-(i+1)]==9:
digits[-(i+1)] = 0
reg = 1
else:
... | 66-plus-one.py | py | 515 | en | python |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if len(lists) == 0:
return lis... | mergeKLists.py | py | 1,359 | en | python |
/*
* @lc app=leetcode.cn id=118 lang=javascript
*
* [118] 杨辉三角
*
* https://leetcode-cn.com/problems/pascals-triangle/description/
*
* algorithms
* Easy (59.29%)
* Total Accepted: 15.7K
* Total Submissions: 26.4K
* Testcase Example: '5'
*
* 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
*
*
*
* 在杨辉三角中,每个数是... | 118.pascals-triangle.js | js | 1,076 | zh | javascript |
package com.qunar.fxd.leetcode.array;
/**
* https://leetcode-cn.com/problems/find-pivot-index/
*
* 输入:
* nums = [1, 7, 3, 6, 5, 6]
* 输出: 3
* 解释:
* 索引3 (nums[3] = 6) 的左侧数之和(1 + 7 + 3 = 11),与右侧数之和(5 + 6 = 11)相等。
* 同时, 3 也是第一个符合要求的中心索引。
*
*
*/
public class PivotIndex {
public int pivotIndex1(int[] nums)... | PivotIndex.java | java | 1,336 | zh | java |
import sys
from collections import deque
def devide(start, N, paper):
mark = paper[start[0]][start[1]]
if N == 1:
if mark == -1: return 1, 0, 0
elif mark == 0: return 0, 1, 0
else : return 0, 0, 1
minusOneCnt, zeroCnt, plusOneCnt = 0, 0, 0
for k in range(3):
f... | solution.py | py | 1,120 | en | python |
class Solution:
def isOneBitCharacter(self, bits):
"""
:type bits: List[int]
:rtype: bool
"""
cnt = 0
for i in range(len(bits) - 2, -1, -1):
if bits[i]==1:
cnt += 1
else:
break
return cnt % 2 == 0
| p717.py | py | 314 | en | python |
/*
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate ... | 4Sum.java | java | 3,574 | en | java |
#include <bits/stdc++.h>
using namespace std;
/*
* Daily leetcode challenge
* 13 June 23
*/
class Solution {
public:
/*
* Brute Force Solution
* Time Complexity = O(N*N*N)
*/
// int equalPairs(vector<vector<int>>& grid) {
//
// int n = grid.size();
// int count = 0;
// f... | EqualRowsEqualColumns.cpp | cpp | 2,075 | en | cpp |
//My code doesn't work for repeated numbers
// class Solution {
// public:
// string originalDigits(string s) {
// map<string,string> nos;
// nos.insert({"0","zero"});
// nos.insert({"1","one"});
// nos.insert({"2","two"});
// nos.insert({"3","three"});
// nos.insert(... | 423-reconstruct-original-digits-from-english.cpp | cpp | 1,998 | uk | cpp |
public class Solution {
public int minMoves(int[] nums) {
if (nums.length == 0) {
return 0;
}
int mn = nums[0];
for (int e : nums) {
mn = Math.min(mn, e);
}
int res = 0;
for (int e : nums) {
res += Math.abs(mn - e);
... | MinimumMovesEqualArrayElements.java | java | 349 | en | java |
class Solution:
def hasAlternatingBits(self, n: int) -> bool:
s = str(bin(n))[2:]
last = s[0]
for i in range(1, len(s)):
if s[i] == last:
return False
last = s[i]
return True
| 0693_BinaryNumberWithAlternatingBits.py | py | 252 | en | python |
import os
import requests
from requests.auth import HTTPBasicAuth
def download_pdf_file(url: str) -> bool:
"""Download PDF from given URL to local directory.
:param url: The url of the PDF file to be downloaded
:return: True if PDF file was successfully downloaded, otherwise False.
"""
# Request... | main.py | py | 1,283 | en | python |
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
res = []
level = [root]
while root and level:
res.append([... | n-ary-tree-level-order-traversal.py | py | 578 | en | python |
class Solution {
// X X X X
// X O O X
// X X O X
// X # X X
static int m, n;
public void solve(char[][] board) {
if (board == null || board.length == 0) return;
m = board.length;
n = board[0].length;
for (int i = 0; i < m; i++) {//行
for (int j = 0; j < ... | [130]被围绕的区域.java | java | 1,451 | en | java |
class Solution {
public int mostFrequentEven(int[] nums) {
int res=Integer.MAX_VALUE;
int count=0;
HashMap<Integer,Integer> map= new HashMap<>();
for(int i:nums){
if(i%2==0){
map.put(i,map.getOrDefault(i,0)+1);
if(count<map.get(i)){
... | 2404-most-frequent-even-element.java | java | 575 | ru | java |
package Leetcode;
import java.util.ArrayList;
import java.util.List;
/**
*给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
*给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
* 输入:"23"
* 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
*/
public class LetterCombinations {
public List<String> letterCombinations(String digits) {
... | LetterCombinations.java | java | 2,243 | en | java |
# I 숫자 큐에 주어진 숫자를 삽입합니다.
# D 1 큐에서 최댓값을 삭제합니다.
# D -1 큐에서 최솟값을 삭제합니다.
# 큐가 비어있다면 [0,0]을 반환한다.
# 큐가 있다면 [최댓값, 최솟값]을 반환한다.
import heapq
def solution(operations):
heap = []
for operation in operations:
oper, number = operation.split()
if oper == "I": # 추가
heapq.heappush(heap, int(number... | 0503_이중우선순위큐.py | py | 998 | ko | python |
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
... | 21. Merge Two Sorted Lists.cpp | cpp | 2,956 | en | cpp |
class Solution {
public:
int robpart(vector<int>& nums){
if(nums.empty())
return 0;
if(nums.size()==1)
return nums[0];
if(nums.size()==2)
return max(nums[0],nums[1]);
int size=nums.size();
vector<int> ans(size,0);
ans[0]=nums[0];
ans[1]... | 213_ROBⅡ.cpp | cpp | 898 | zh | cpp |
////////// sol 1 HashMap
class Solution {
public List<String> topKFrequent(String[] words, int k) {
// count freq with hashmap
HashMap<String, Integer> map = new HashMap<>();
for (String w : words) {
map.put(w, map.getOrDefault(w, 0) + 1);
}
// sort freq... | LC692.java | java | 1,679 | en | java |
package main
import (
"fmt"
)
/*
https://leetcode.cn/problems/encode-and-decode-tinyurl/
535. TinyURL 的加密与解密
TinyURL 是一种 URL 简化服务, 比如:当你输入一个 URL https://leetcode.com/problems/design-tinyurl 时,它将返回一个简化的URL http://tinyurl.com/4e9iAk 。请你设计一个类来加密与解密 TinyURL 。
加密和解密算法如何设计和运作是没有限制的,你只需要保证一个 URL 可以被加密成一个 TinyURL ,并且这个 Tin... | main.go | go | 2,066 | zh | go |
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
class Solution:
"""
@param head: n
@return: The new head of reversed linked list.
"""
def reverse(self, head):
self.tail = head
self.helper(head.next, head)
r... | 35_Reverse_Linked_List.py | py | 1,170 | en | python |
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
//Runtime: 8 ms, faster than 22.84%
//Memory Usage: 11.1 MB, less than 28.17%
// 采用二分法啦,然后由于会使用左右边界的值来辅助查找,所以采用第一种写法lhs <= rhs
int search(vector<int>& nums, int target) {
int lhs = 0, rhs = nums.size()-1;
... | main.cpp | cpp | 2,344 | en | cpp |
/*
* @lc app=leetcode id=154 lang=golang
*
* [154] Find Minimum in Rotated Sorted Array II
*/
package q00154
// @lc code=start
func findMin(nums []int) int {
l ,r := 0, len(nums) - 1
for l < r {
mid := (l + r) / 2
if nums[l] > nums[mid] {
r = mid
} else if nums[mid] > nums[r] {
l = mid + 1
}... | 154.find-minimum-in-rotated-sorted-array-ii.go | go | 424 | en | go |
import itertools
def solution(k, dungeons):
answer = 0
n = len(dungeons)
arr = [x for x in range(n)]
for w in itertools.permutations(arr, n):
tired = k
temp = 0
for i in w:
v = dungeons[i]
if v[0] <= tired:
tired -= v[1]
... | 피로도.py | py | 437 | en | python |
from typing import List
class Solution:
# O(N) time | O(1) space
def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int:
pairs = sorted([(gt, pt)
for gt, pt in zip(growTime, plantTime)], reverse=True)
res = time = 0
for gTime, pTime in pair... | 4. earliestFullBloom.py | py | 410 | en | python |
class Solution {
public String solution(String s) {
StringBuilder sb = new StringBuilder();
String[] splitS = s.split("");
int index = 0;
for(String str : splitS) {
if(str.equals(" ")) {
sb.append(" ");
index = 0;... | JadenCase 문자열 만들기.java | java | 536 | en | java |
package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
// write your code here
}
}
class MagicDictionary {
Map<Integer, List<String>> map;
public MagicDictionary() {
map = new HashMap<>();
}
public void buildDict(String[] dictionary) {... | Main.java | java | 1,275 | en | java |
/*
* Author: Deean
* Date: 2023-08-13 22:34
* FilePath: algorithm
* Description:2810. 故障键盘
*/
/**
* @param {string} s
* @return {string}
*/
var finalString = function (s) {
let stack = [];
for (const c of s) {
if (c === 'i') {
stack.reverse();
} else {
stack.push... | P2810. 故障键盘.js | js | 421 | en | javascript |
class Solution{
public:
int inSequence(int a, int b, int c){
if(a == b) return 1;
if(!c) return a == b;
if(abs(b - (a + c)) > abs(b - a)) return 0;
double d = (double) (b - a) / c;
int i = (b - a) / c;
return d - i == 0;
}
/*
a + (n * c) = b
... | Arithmetic Number.cpp | cpp | 368 | en | cpp |
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def numOfWays(self, nums: List[int]) -> int:
def bc(n, k):
if(k > n - k):
k = n - k
res = 1
... | 1569--Number-of-Ways-to-Reorder-Array-to-Get-Same-BST-Hard.py | py | 1,254 | en | python |
import java.util.Arrays;
public class IncreasingTriplet {
public boolean increasingTriplet(int[] nums) {
int first_num = Integer.MAX_VALUE;
int second_num = Integer.MAX_VALUE;
for (int n: nums) {
if (n <= first_num) {
first_num = n;
} else if (n <= se... | IncreasingTriplet.java | java | 807 | en | java |
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
double result=0.0;
vector<int> v;
int i,j;
int mid=(nums1.size()+nums2.size())/2;
for(i=0,j=0;i+j<mid+1;){
if(... | head.h | h | 883 | en | c |
<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>理解Objective-C Runtime(四)Method Swizzling | 张不坏的博客</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=3, minimum-scale=1">
<meta name="author" content="张不坏">
<meta name="descri... | index.html | html | 35,832 | en | html |
//
// LIS.swift
// LeeCode
//
// Created by Ocean on 2022/3/19.
//
/*
给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。
子序列 是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。
示例 1:
输入:nums = [10,9,2,5,3,7,101,18]
输出:4
解释:最长递增子序列是 [2,3,7,101],因此长度为 4 。
示例 2:
输入:nums = [0,1,0,3,2,3]
输出:4
示例 3:... | LIS.swift | swift | 2,221 | zh | swift |
class Solution:
# @param A : tuple of integers
# @return a list of integers
def repeatedNumber(self, A):
N = len(A)
sumN = sum(A)
sumSetN = sum(set(A))
sumNnum = (N*(N + 1))//2
repeatN = sumN - sumSetN
missingN = repeatN + (sumNnum - sumN)
return(repea... | ReapeatAndMissingNumberArray.py | py | 334 | en | python |
#
# @lc app=leetcode id=1360 lang=python
#
# [1360] Number of Days Between Two Dates
#
# @lc code=start
class Solution(object):
def daysBetweenDates(self, date1, date2):
"""
:type date1: str
:type date2: str
:rtype: int
"""
days = [(153 * i + 8) // 5 for i in range... | 1360.number-of-days-between-two-dates.py | py | 425 | en | python |
import java.math.BigInteger;
class Solution {
public int solution(int balls, int share) {
int answer =0;
BigInteger ballsFactorial = BigInteger.ONE;
BigInteger shareFactorial = BigInteger.ONE;
BigInteger shareFactorials = BigInteger.ONE;
for(int i =1; i<=balls;i++ ) {
ballsFactorial=ballsFactorial.mult... | 구슬을 나누는 경우의 수.java | java | 723 | en | java |
"""
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 1... | 74. Search a 2D Matrix.py | py | 2,803 | en | python |
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if(!root) return false;
if(!root->left && !r... | 112_Path Sum.cpp | cpp | 2,017 | en | cpp |
#include <iostream>
using namespace std;
class Solution {
public:
bool isPowerOfTwo(int n) {
if (n <=0)
{
return false;
}
//power of 2 has only one of `1`, so we can use this trick.
return !(n & (n - 1));
}
}; | isPowerOfTwo.cpp | cpp | 234 | en | cpp |
def solution(nums):
answer = 0
l = len(nums)/2
ans = []
for i in range(0, len(nums)):
if nums[i] not in ans :
ans.append(nums[i])
if len(ans) >= l :
answer = l
else :
answer = len(ans)
return answer
| 48 폰켓몬.py | py | 274 | en | python |
class Solution {
public:
int dfs(int i,int j,vector<vector<int>>& matrix,int prev, vector<vector<int>>&dp){
int n=matrix.size();
int m=matrix[0].size();
if(i<0||j<0||i>=n||j>=m||matrix[i][j]<=prev){
return 0;
}
if(dp[i][j]!=-1){
return dp[i][j];... | 329-longest-increasing-path-in-a-matrix.cpp | cpp | 1,052 | en | cpp |
class Solution:
def maximumGood(self, statements: List[List[int]]) -> int:
n = len(statements)
res = 0
def check(s):
for i in range(n):
if (s>>i)&1 == 1:
for j in range(n):
if statements[i][j] == 2:
... | solution.py | py | 604 | en | python |
package mcw.test.leetcode.niuke;
/**
* @author mcw 2020\3\14 0014-19:45
*
* 假设你有一个数组,其中第 i 个元素是某只股票在第 i 天的价格。
* 设计一个算法来求最大的利润。 最多可以进行两次交易。 注意: 不能同时进行多个交易(即,必须在再次购买之前出售之前的股票)
*/
public class Test28 {
public static int maxProfit(int[] arr) {
int min1 = Integer.MIN_VALUE, min2 = Integer.MIN_VALUE, ma... | Test28.java | java | 974 | zh | java |
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <sys/time.h>
class Solution {
public:
// 利用stl求解
std::string LeftRotateString1(std::string str, int n) {
if (str.empty() || n <= 0 || n >= str.size()) {
return str;
}
return str.substr(n, str... | 43_左旋转字符串.cpp | cpp | 2,217 | en | cpp |
'''给出两个非空的链表用来表示两个非负的整数。
其中,它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储一位数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self... | 2-两数相加.py | py | 1,399 | zh | python |
#include<vector>
#include<map>
#include<string>
#include<queue>
#include<sstream>
#include<stack>
#include<set>
#include<unordered_map>
using namespace std;
/*
Given two Sparse Matrix A and B, return the result of AB.
You may assume that A's column number is equal to B's row number.
*/
/**
* @param A: a sparse mat... | 311(Lint654)Sparse Matrix Multiplication.cpp | cpp | 1,466 | en | cpp |
/*
* Problem: 388. Longest Absolute File Path [medium]
* Source : https://leetcode.com/problems/longest-absolute-file-path/description/
* Solver : Baur Krykpayev
* Date : 06/19/2018
*/
class Solution {
public:
int lengthLongestPath(string input)
{
unordered_map<int,int> levels;
levels... | 388. Longest Absolute File Path.cpp | cpp | 1,059 | en | cpp |
package BasicLinkedList.Q876;
import BasicLinkedList.ListNode;
public class Solution {
public ListNode middleNode(ListNode head) {
ListNode dummy = new ListNode();
dummy.next = head;
ListNode fast = dummy;
ListNode slow = dummy;
while(fast != null && fast.next != null) {
slow = slow.next;... | Solution.java | java | 433 | en | java |
from typing import List
class Solution:
def numIslands(self, g: List[List[str]]) -> int:
n = len(g)
m = len(g[0])
color = 1
grid = []
for i in range(n):
r = [0] * m
grid.append(r)
for i in range(n):
for j in range(m):
... | NumOfIslands.py | py | 1,453 | en | python |
#include <limits.h>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int n = coins.size();
vector<int> dp(amount + 1, INT_MAX);
dp[0] = 0;
for (int coin : coins) {
//完全背包,必须正序遍历
for (int i = coin; i <= a... | 322.coin-change.cc | cc | 714 | en | cpp |
public class Solution {
/**
* @param nums: an integer unsorted array
* @param k: an integer from 1 to n
* @return: the kth largest element
*/
public int kthLargestElement2(int[] nums, int k) {
// write your code here
Queue<Integer> heap = new PriorityQueue<Integer>(k);
... | 606_Kth largest element.java | java | 532 | en | java |
package leetcode_solutions.arrays;
import java.util.ArrayList;
import java.util.List;
public class PositionsofLargeGroups830 {
public List<List<Integer>> largeGroupPositions(String S) {
char[] chs = S.toCharArray();
List<List<Integer>> ans = new ArrayList<>();
int start = 0;
for (... | PositionsofLargeGroups830.java | java | 1,002 | en | java |
// 20:08-20:28
/**
* 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:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int... | 113.cpp | cpp | 1,263 | en | cpp |
class Solution {
public boolean checkValid(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return true;
}
int row = matrix.length;
int col = matrix[0].length;
for (int i=0; i<row; i++) {
int rowWiseXor = 0;
int colWiseXor = 0;... | 2133_Check_If_Every_Row_Column_Contains_All_Numbers.java | java | 623 | en | java |
// 69. Sqrt(x)
class Solution {
public:
int mySqrt(int x) {
int l=1,h=x;
int ans=0;
while(l<=h){
long long int mid=l+(h-l)/2;
if(mid*mid>x){
h=mid-1;
}
else{
ans=mid;
l=mid+1;
}
... | Sqrt.cpp | cpp | 667 | en | cpp |
// t:n^3 s:n^2
// this question is equal to two people from upper left to lower right
class Solution {
public int cherryPickup(int[][] grid) {
int n = grid.length;
int[][] state = new int[n][n];
state[0][0] = grid[0][0];
for (int step = 1; step < 2 * n - 1; step++) {
// w... | 741. Cherry Pickup.java | java | 1,910 | en | java |
from typing import List
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
kvmaps = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
res = []
self.dfs(digits, 0, res, '', kvmaps)
return res
def dfs(self, st... | PhoneCombinations.py | py | 568 | en | python |
class Solution {
public:
int ans = 0, min_cost = 1e9;
int n;
void dfs(int u, int sum, vector<int>& a, int target) {
if (abs(sum - target) < min_cost) {
min_cost = abs(sum - target);
ans = sum;
} else if (abs(sum - target) == min_cost && sum < ans) {
ans =... | LeetCode1774.cpp | cpp | 776 | en | cpp |
// https://leetcode.com/problems/excel-sheet-column-number/
class Solution {
public:
int titleToNumber(string s) {
int n = s.length(), res = 0;
for(int i = n-1; i>=0; i--) res += ((s[i]-'A'+1)*pow(26, n-1-i));
return res;
}
}; | 171.cpp | cpp | 259 | en | cpp |
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
occ = {}
for i in nums:
occ[i] = occ.get(i, 0) + 1
bucket = [[] for _ in range(len(nums) + 1)]
for val, occ in occ.items():
bucket[occ].append(val)
... | 347_top_k_freq_elem.py | py | 1,129 | en | python |
/*
* [166] Fraction to Recurring Decimal
*
* https://leetcode.com/problems/fraction-to-recurring-decimal/description/
*
* algorithms
* Medium (17.99%)
* Total Accepted: 61K
* Total Submissions: 339.3K
* Testcase Example: '1\n5'
*
* Given two integers representing the numerator and denominator ... | 166.fraction-to-recurring-decimal.cpp | cpp | 2,284 | en | cpp |
#include <iostream>
#include "vector"
#include "queue"
using namespace std;
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), lef... | main.cpp | cpp | 1,188 | en | cpp |
#include <stack>
#include <iostream>
using namespace std;
bool checkString(string in) {
stack<char> s;
for (int j = 0; j < in.length(); j++) {
if (in[j] == '(' || in[j] == '[') {
s.push(in[j]);
}
else {
if (s.empty()) {
return false;
... | CP1-1.cpp | cpp | 880 | ru | cpp |
package leetcode_study_badge.algorithm
class Day7 {
fun floodFill(image: Array<IntArray>, sr: Int, sc: Int, newColor: Int): Array<IntArray>? {
val color = image[sr][sc]
if (color != newColor) dfs(image, sr, sc, color, newColor)
return image
}
private fun dfs(image: Array<IntArray>,... | Day7.kt | kt | 729 | en | kotlin |
package com.leo.leetcode.point;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* 532. 数组中的K-diff数对
* https://leetcode-cn.com/problems/k-diff-pairs-in-an-array/description/
*/
public class T532 {
public int findPairs(int[] nums, int k) {
if (nums.length == 0 || k < 0) {
... | T532.java | java | 960 | en | java |
#include <string.h>
#include <stdio.h>
#define maxL 10000
#define maxR 10000
char conS[maxL] = {};
int rowStart[maxR] = {};//the i'th row of converted string starts on index rowStart[i] of conS[]
int rowCount[maxR] = {};//count put char in conS for each row
char* convert(char* s, int numRows) {
int len = strlen(s), zi... | convert.c | c | 1,634 | en | c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.