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/two-sum
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize)
{
*returnSize = 2; //need to give returnSize his lenght!
int i = 0;
int j = 1;
int* array = (int*)malloc(2*siz... | Solution.c | c | 678 | en | c |
/* Problem - https://leetcode.com/problems/merge-k-sorted-lists/ */
/* By Sanjeet Boora */
/**
* 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... | mergeKLists.cpp | cpp | 1,177 | en | cpp |
func filterRestaurants(restaurants [][]int, veganFriendly int, maxPrice int, maxDistance int) []int {
data := make([][]int, 0)
for _, s := range restaurants {
if s[2] >= veganFriendly && s[3] <= maxPrice && s[4] <= maxDistance {
data = append(data, s)
}
}
sort.Slice(data... | 1333.go | go | 593 | en | go |
# https://leetcode.com/problems/implement-strstr/
# Problem Description
# Solution
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
needleIdx = -1
idx = 0
needlePos = 0
size = len(haystack)
needleSize = len(needle)
if needleSize... | implement-strstr.py | py | 2,036 | en | python |
package leetcode.solution.n1721
import leetcode.util.ListNode
/**
* [1721. Swapping Nodes in a Linked List](https://leetcode.com/problems/swapping-nodes-in-a-linked-list/)
*/
class Solution {
fun swapNodes(head: ListNode?, k: Int): ListNode? {
val nullNode = ListNode(-1).also { it.next = head }
... | Solution.kt | kt | 1,088 | en | kotlin |
package main
// github.com/EndlessCheng/codeforces-go
func minTimeToType(s string) int {
cur := 'a'
ans := len(s)
for _, b := range s {
d := int(b - cur)
if d < 0 {
d = -d
}
ans += min(d, 26-d)
cur = b
}
return ans
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
| a.go | go | 300 | en | go |
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int stoneGameV(vector<int>& stoneValue) {
/*vector<int> sumValues;
int sum = 0;
for( int i = 0 ; i < stoneValue.size() ; ++i ){
sum += stoneValue[i];
sumValues.push_back(sum);
}*/
// 1 1 2
// 0 2 3
int r... | stgame.cpp | cpp | 1,385 | en | cpp |
package hackerrankchallenges.Days10OfStatistics;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class SolutionInterquartileRange {
public static void main(String[]args){
Scanner ui = new Scanner(System.in);
int sizeR = ui.nextInt();
int [] elem... | SolutionInterquartileRange.java | java | 974 | en | java |
class Solution:
def solveSudoku(self, board) -> None:
"""
Do not return anything, modify board in-place instead.
"""
rows = collections.defaultdict(set)
cols = collections.defaultdict(set)
boxes = collections.defaultdict(set)
seen = collections.deque([])
... | LeetCode 37 Sudoku Solver.py | py | 1,518 | en | python |
package _200_299
import "sort"
/*
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array,
and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
O... | 217_contains_duplicate.go | go | 779 | en | go |
package com.bhavesh.solutions;
public class Leetcode190 {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int ans = 0;
for (int i = 0; i < 32; i++) {
ans = ans << 1;
if ((n & 1) == 1) {
ans++;
}
n = n >> 1;
}
return ans;
}
// Same solution as above but with a di... | Leetcode190.java | java | 695 | en | java |
// top down dp/recursion approach O(N*M) space and time
class Solution {
public:
int ways(int x,int y,vector<vector<int>> &dp,int m,int n){
if(x>=m || y >= n)
return 0;
if(x==m-1 && y == n-1)
return 1;
if(dp[x][y] != -1) return dp[x][y];
return dp[x]... | 4.uniquePath.cpp | cpp | 1,003 | en | cpp |
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
lenA = self.getLength(headA)
lenB = self.getLength(headB)
# 通过移动较长的链表,使两链表长度相等
if l... | Leetcode_160_IntersectionOfTwoLinkedList.py | py | 1,538 | en | python |
package com.lmz.leetcode.practice.dp.add_binary_search;
import com.lmz.algorithm_learning.leetcode.TransformUtil;
import java.util.Arrays;
import java.util.TreeMap;
/**
* @author: limingzhong
* @create: 2022-10-22 9:28
*/
public class JobScheduling1235 {
/**
*动态规划+TreeMap
*/
public int jobSchedu... | JobScheduling1235.java | java | 1,639 | en | java |
//https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<bool> vec(nums.size()+1, false);
vector<int> result;
for(int i = 0; i < nums.size(); i++)
if(nums[... | find_all_numbers_disappeared_in_an_array.cpp | cpp | 543 | en | cpp |
package Cruise;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Q2 {
public static void main(String[] args) {
}
public static String writeIn(List<String> ballot) {
if (ballot.size() == 0) return "";
else if (ballot.size() == 1... | Q2.java | java | 1,662 | en | java |
package main
import "fmt"
/* 0ms */
func totalNQueens(n int) (res int) {
col := make([]bool, n)
diag1 := make([]bool, n*2)
diag2 := make([]bool, n*2)
var dfs func([]int)
dfs = func(q []int) {
x := len(q)
if x == n {
res++
return
}
for y := 0; y < n; y++ {
d1 := x + y
d2 := x - y + n
if co... | main.go | go | 620 | en | go |
package main.scala
/**
给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。
示例 1:
nums1 = [1, 3]
nums2 = [2]
则中位数是 2.0
示例 2:
nums1 = [1, 2]
nums2 = [3, 4]
则中位数是 (2 + 3)/2 = 2.5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays... | FindMedianSortedArrays.scala | scala | 3,977 | en | scala |
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
/**
* Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
Each element in the result must be unique.
The result can be in any order.
... | Intersection_of_Two_Arrays.java | java | 1,502 | en | java |
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
vector<int> v(n);
for(int i=0;i<n;i++)
cin>>v[i];
int k;
cin>>k;
int j=n-1;
for(int i=0;i<n;i++)
{
if(v[i]==k)
{
while(j>i)
{
if(v[i]!=v[j])
{
swap(v[i],v[j]);
break;
}
j--;
}
if(j<=i)
{
... | RemoveElement.cpp | cpp | 433 | ja | cpp |
package cn.xj.code;
/**
* Find the contiguous subarray within an array (containing at least one number)
* which has the largest sum.
*
* For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray
* [4,-1,2,1] has the largest sum = 6.
*
* @author alanfeng
*
*/
public class MaximumSubarray ... | MaximumSubarray.java | java | 1,602 | en | java |
# Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
... | 103_binary_tree_zigzag_traversal.py | py | 1,096 | en | python |
#include<iostream>
#include<vector>
#include<string>
#include<stack>
#include<queue>
#include<algorithm>
#include<deque>
#include<math.h>
#include<map>
#include<unordered_map>
#include<set>
#include<unordered_set>
using namespace std;
class Solution {
public:
int carFleet(int target, vector<int>& position, vector... | M_carFleet.cpp | cpp | 411 | en | cpp |
public class Codec {
Map<Integer,String> map = new HashMap();
String prefix = "http://tinyurl.com/";
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
int code = longUrl.hashCode();
String shortUrl = prefix + code;
map.put(shortUrl.hashCode(),longUrl);
... | 535.java | java | 629 | en | java |
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode he... | 61-rotate-list.java | java | 1,080 | en | java |
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
const int m = grid.size();
const int n = grid[0].size();
vector< vector<int> > dp(m);
for (int i = 0; i < m; ++i) {
... | Minimum_Path_Sum.cpp | cpp | 895 | en | cpp |
package leetcode.easy;
//Climbing Stairs
public class Q070 {
//fibnacchi
//only two ways to get n
//from n-1
//from n-2
//forget you can reach n from n-2 by two*1 step
//this is covered by "from n-1"
//so get n = (n-1)+(n-2)
//then for N=n+1
//the previous n now is N-1
//the previous n-1 now is N-2
//t... | Q070.java | java | 1,244 | en | java |
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function (nums) {
for (var i = 0, j = 0; j < nums.length; j++) {
if (nums[j] !== 0) {
if (j !== i) {
nums[i] = nums[j];
nums[j] = 0;
... | Q283.js | js | 361 | en | javascript |
function findKthPositive(arr: number[], k: number): number {
let sets: Set<number> = new Set<number>(arr);
let ans: number[] = [];
for (let i = 1; i <= 2000; i++) {
if (!sets.has(i)) {
ans.push(i);
}
}
let count = 0;
for (let i = 0; i < ans.length; i++) {
const cur = ans[i];
count += ... | kth-missing-positive-number.ts | ts | 488 | en | typescript |
package com.leammin.leetcode.medium;
import com.leammin.leetcode.struct.ListNode;
/**
* 24. 两两交换链表中的节点
*
* <p>给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。</p>
*
* <p><strong>你不能只是单纯的改变节点内部的值</strong>,而是需要实际的进行节点交换。</p>
*
* <p> </p>
*
* <p><strong>示例:</strong></p>
*
* <pre>给定 <code>1->2->3->4</code>, 你应... | SwapNodesInPairs.java | java | 1,368 | en | java |
from typing import List
class Solution:
def search(self, nums: List[int], target: int) -> int:
l = 0
r = len(nums) - 1
while l <= r:
t = l + (r - l) // 2
if nums[t] > target:
r = t - 1
elif nums[t] < target:
l = t + 1
... | Binary Search.py | py | 425 | en | python |
package lc125ValidPalindrome;
/*
125. 验证回文串
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:
输入: "race a car"
输出: false
*/
public class Solution {
public boolean isPalindrome(String s) {
if (s == null || s.length() == 0) {
... | Solution.java | java | 1,025 | zh | java |
package Trees;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class Node {
public int value;
public Node left;
public Node right;
public Node(){
this(0);
}
public Node(int value){
this.value=value;
}
public static void preOrder(No... | Node.java | java | 3,328 | en | java |
package 二叉树;
/**
* https://leetcode-cn.com/problems/invert-binary-tree/
*
*
* 给定一个二叉树,找出其最大深度。
* 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
*
* 输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
*
*/
public class _226_翻转二叉树 {
public TreeNode invertTree(TreeN... | _226_翻转二叉树.java | java | 682 | zh | java |
class Solution {
public:
int maxProduct(vector<int>& nums) {
int pdt=1;
int maxi=INT_MIN;
for(int i=0;i<nums.size();i++){
pdt=pdt*nums[i];
maxi=max(pdt,maxi);
if(pdt==0){
pdt=1;
}
}
pdt=1;
for(int i=nums.... | 0152-maximum-product-subarray.cpp | cpp | 501 | zh | cpp |
"""
695. Max Area of Island
Medium
You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
The area of an island is the number of cells with a value 1 in the isla... | max-area-of-island.py | py | 5,385 | en | python |
package com.tmosest.competitiveprogramming.leetcode.easy;
class DeleteColumnsToMakeSorted {
/* Write code here. */
/**
* Determine the number of columns to delete to make sorted.
*
* @param arr The input array of strings.
* @return The number of deletes.
*/
public int minDeletionSize(String[] arr... | DeleteColumnsToMakeSorted.java | java | 584 | en | java |
/*
* @lc app=leetcode.cn id=66 lang=javascript
*
* [66] 加一
*
* https://leetcode-cn.com/problems/plus-one/description/
*
* algorithms
* Easy (37.66%)
* Total Accepted: 40K
* Total Submissions: 106.3K
* Testcase Example: '[1,2,3]'
*
* 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
*
* 最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。... | 66.加一.js | js | 1,256 | zh | javascript |
public class Question096 {
int[] dp = new int[20];
{
dp[0] = 1;
dp[1] = 1;
}
public static void main(String[] args) {
Question096 question096 = new Question096();
question096.numTrees(3);
}
public int numTrees(int n) {
for (int i = 2; i <= n; i++) {
... | Question096.java | java | 467 | en | java |
/*
Say you have an array, A, for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Return the maximum possible profit.
Input Format:
The fi... | BestTimeToBuyAndSellStocks_I.java | java | 1,046 | en | java |
package online;
import java.util.ArrayList;
public class PalindromePartitioning {
public ArrayList<ArrayList<String>> partition(String s) {
if(s.length()==0||s==null){
return null;
}
ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
ArrayList<String> item= new ArrayList<String>();
... | PalindromePartitioning.java | java | 2,129 | en | java |
/*
* @lc app=leetcode.cn id=1049 lang=javascript
*
* [1049] 最后一块石头的重量 II
*/
// @lc code=start
/**
* @param {number[]} stones
* @return {number}
*/
var lastStoneWeightII = function(stones) {
/**
* 这是一道阅读理解题?
* 题目的描述,倒是看的很清楚,
* 选两块石头,如果两块石头重量相等,那么都粉碎
* 如果两块是否不等,那么就是 stone[a] - stone[b] 放数组里
* 然后循... | 1049.最后一块石头的重量-ii.js | js | 3,961 | zh | javascript |
package leetcode
// https://leetcode-cn.com/problems/lru-cache/
// 146. LRU缓存机制
type LRUCache struct {
capacity int
cacheMap map[int]*Node
first *Node
last *Node
}
type Node struct {
key int
val int
next *Node
prev *Node
}
func newNode(k, v int) *Node {
return &Node{
key: k,
val: v,
}
}
fun... | 146.lru-cache.go | go | 1,404 | en | go |
package com.review;
import java.util.Scanner;
public class Area {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m;
m = Integer.parseInt(in.nextLine().trim());
String[] sArrays = new String[m];
sArrays[0] = in.nextLine();
int n = ... | Area.java | java | 2,844 | en | java |
package leetcode.dsa.easy;
/*
* /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class ListNode {
int ... | Add2Numbers_2.java | java | 1,560 | en | java |
package com.vkeonline.leetcode.p1700;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.PriorityQueue;
/**
* Leetcode [E]: 1710: Maximum Units on a Truck
* @author csgear
*/
public class MaximumUnitsOnTruck {
public int maximumUnits(int[][] boxTypes, int truckSize) {
PriorityQue... | MaximumUnitsOnTruck.java | java | 815 | en | java |
class ListNode():
def __init__(self,x):
self.val = x
self.next = None
class Solution():
def addTwoNumbers(self,l1,l2):
if not l1 and not l2:
return 0
#first instance a dummy node to begin
dummy = ListNode(0)
cur = dummy
tmp = 0
add = 0
... | 2addTwoNumbers.py | py | 922 | en | python |
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
std::unordered_map<string, vector<string>> hash;
for(int i = 0; i < strs.size(); i++) {
auto str = strs[i];
std::sort(str.begin(), str.end());
if(hash.find(str) != hash.end(... | 49_1.cpp | cpp | 602 | en | cpp |
/**
* @param {string[]} dictionary
* @param {string} sentence
* @return {string}
*/
const replaceWords = (dictionary, sentence) => {
const arr = sentence.split(' ');
return arr
.map((word) => {
let curRoot = null;
for (const root of dictionary) {
if (word.startsWith(root)) {
if... | 648.js | js | 507 | en | javascript |
// The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
// Given two integers x and y, calculate the Hamming distance.
// Note:
// 0 ≤ x, y < 231.
// Input: x = 1, y = 4
// Output: 2
// Explanation:
// 1 (0 0 0 1)
// 4 (0 1 0 0)
↑ ↑
class Solut... | hammingDistance.cpp | cpp | 698 | en | cpp |
import java.util.*;
class Solution {
public int solution(int[] scoville, int K) {
int answer = 0;
PriorityQueue<Integer> queue = new PriorityQueue<>();
for(int scv : scoville) {
queue.add(scv);
}
while (queue.peek() < K && queue.size() > 1) {
... | 더 맵게.java | java | 597 | en | java |
# Longest Increasing Path in a Matrix
class Solution(object):
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not any(matrix): return 0
m, n = len(matrix), len(matrix[0])
memo = [[0] * n for _ in range(m)]
... | longest_increasing_path.py | py | 989 | en | python |
#include "lc.h"
class Solution {
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
for (auto &vec : A)
{
size_t len = A.size();
size_t i = 0;
for ( ; i < len / 2; ++i)
{
int left = vec[i];
... | lc832.cpp | cpp | 932 | en | cpp |
class Solution{
public:
using ll = long long int;
ll mod = 1e9 + 7;
ll modpow(ll a, ll b)
{
ll x = 1%mod;
a %= mod;
while(b)
{
if(b&1)
x = (x*a)%mod;
a = (a*a)%mod;
b >>= 1;
}
return x;
}
ll modinverse(ll a)
{
return modpow(a,mod-2);
}
... | Count even length.cpp | cpp | 563 | en | cpp |
# Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).
# The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).
# You may return the answer in any order. The answe... | k-closet-poins-to-origin.py | py | 1,429 | en | python |
package list.easy;
import pub.ListNode;
import java.util.ArrayList;
import java.util.List;
/**
* 剑指 Offer 06. 从尾到头打印链表
*/
public class 从尾到头打印链表 {
// public static void main(String[] args) {
// ListNode head = new ListNode(1);
// head.next = new ListNode(3);
// head.next.next = new ListNode... | 从尾到头打印链表.java | java | 1,347 | ar | java |
package com.interview.sde.java.string;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//https://leetcode.com/problems/group-anagrams/
public class GroupAnagrams {
static List<List<String>> groupAnagrams(String[] strs) {
final int OFFSET = 97;
M... | GroupAnagrams.java | java | 1,153 | en | java |
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
List<Integer> A = new ArrayList<Intege... | Java Negative Subarray.java | java | 800 | en | java |
package crackingleetcode;
/**
* Given a linked list, swap every two adjacent nodes and return its head.
* You may not modify the values in the list's nodes, only nodes itself may be changed.
*
* @author 58212
* @date 2019-12-26 0:55
*/
public class SwapNodesinPairs_24 {
public class ListNode {
int v... | SwapNodesinPairs_24.java | java | 1,203 | en | java |
"""
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
"""
def longest_conse_slow(arr): #nlogn solution
arr= sorted(arr)
li =[]
max_sequence= 0
count = 1
i=0
while i+1 < len(arr):
if arr[i]+... | Longest_Consecutive_Sequence.py | py | 1,272 | en | python |
package com.company;
import java.util.*;
import java.util.ArrayList;
public class M_384 {
public static void main(String[] args) {
}
class Solution {
ArrayList<Integer>arr=new ArrayList<>();
ArrayList<Integer> rese=new ArrayList<>();
public Solution(int[] nums) {
for(... | M_384.java | java | 901 | en | java |
class Solution {
public:
string removeKdigits(string num, int k) {
int n = num.length();
if(n==k) return "0";
stack<int> s;
string ans="";
for(int i=0;i<n;i++){
int val = num[i]-'0';
while(!s.empty() and val<s.top() and k>0){
s.... | 402-remove-k-digits.cpp | cpp | 729 | ru | cpp |
class Solution {
public:
int maxNonOverlapping(vector<int>& a, int k) {
multiset<int>s;
s.insert(0);
int sum=0;
int cnt=0;
int n=a.size();
for(int i=0;i<n;i++){
sum+=a[i];
if(s.find(sum-k)!=s.end()){
cnt++;
s.cle... | Maximum Number of Non-Overlapping Subarrays With Sum Equals Target.cpp | cpp | 406 | en | cpp |
// 131. Palindrome Partitioning
// https://leetcode.com/problems/palindrome-partitioning/
/**
* @param {string} s
* @return {string[][]}
*/
var partition = function (s) {
const result = [];
backtracking(0, []);
return result;
function backtracking(start, parts) {
if (start === s.length) {
result.p... | app.js | js | 1,058 | en | javascript |
from math import sqrt
def solution(N):
maxs = int(sqrt(N))
for i in range(maxs, 0, -1):
if N%i == 0:
return 2 * (i + N//i)
print(solution(30))
| min_perimeter_rectangle.py | py | 179 | en | python |
fn main() {
// 先把高的人放好即可
let v = vec![vec![7,0],vec![4,4],vec![7,1],vec![5,0],vec![6,1],vec![5,2]];
assert_eq!(vec![vec![5,0],vec![7,0],vec![5,2],vec![6,1],vec![4,4],vec![7,1]], reconstruct_queue(v));
}
pub fn reconstruct_queue(people: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let mut people = people;
peop... | main.rs | rs | 524 | en | rust |
# Time O(n)
# Space O(1)
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
result, opt = float("-inf"), float("-inf")
for n in nums:
opt = max(opt+n,n)
result = max(result,opt)
return result
"""
opt[i] = maximum sum achieved for an array ending at in... | 0053-maximum-subarray.py | py | 1,683 | en | python |
package leetcode.common.Third100;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Jason on 7/2/16.
* Group Shifted Strings
*
* Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "s... | Solution249.java | java | 1,436 | en | java |
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <string>
#include <cstring>
using namespace std;
#define REP(i,n) for(int i=0;i<(n);++i)
#defin... | combine.cpp | cpp | 1,420 | en | cpp |
package leetcode.ReorderList;
import leetcode.common.ds.ListNode;
/**
* Created with IntelliJ IDEA.
* User: ymyue
* Date: 2/8/14
* Time: 11:14 AM
* To change this template use File | Settings | File Templates.
*/
public class Solution {
public void reorderList(ListNode head) {
// IMPORTANT: Please r... | Solution.java | java | 1,286 | en | java |
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
/*
* 来源: LeetCode
* 题目: 最长连续序列(Longest Consecutive Sequence)
*
* 描述:
* 给定一个未排序的整数数组,找出最长连续序列的长度
* 要求算法的时间复杂度为 O(n)
*
* 示例:
* 输入: [100, 4, 200, 1, 3, 2]
* 输出: 4
* 解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4
*
*
* 思路:
* 中心插值
... | 0128. 最长连续序列.cpp | cpp | 1,520 | zh | cpp |
// LeetCode JavaScript
// 6. ZigZag Conversion
// https://leetcode.com/problems/zigzag-conversion/
var convert = function(s, numRows) {
const arr = []
for (let i = 0; i < numRows; i++) arr.push([])
// numsRows가 1이면 한줄에 모두 표현하면 되므로 바로 return s
if (numRows == 1) return s
for (let i = 0; i < s.length; i++) ... | 6_ZigZag_Conversion.js | js | 946 | ko | javascript |
impl Solution {
// Create an output vector and a num vector. Num vector will contain list of numbers and a marker variable will keep a track of which was the last 'prev' value that was added in output vector.
pub fn last_visited_integers(words: Vec<String>) -> Vec<i32> {
let mut output = Vec::n... | 02899. Last Visited Integers.rs | rs | 928 | en | rust |
# 2020.07.18
# Problem Statement:
# https://leetcode.com/problems/longest-common-prefix/
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
# initialize answer
answer = ""
# check empty list
if len(strs) == 0:
return answer
#... | q14.py | py | 949 | en | python |
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
vector<int> result = mergeSortedArrays(nums1, nums2);
int size = result.size();
if (size % 2 == 0) {
return (result[size / 2 - 1] + result[size / 2]) / 2.0;
} else {
... | 4. Median of Two Sorted Arrays.cpp | cpp | 999 | en | cpp |
#include <iostream>
#include <vector>
using namespace std;
// Definition for an interval.
struct Interval {
int start;
int end;
Interval() : start(0), end(0) {}
Interval(int s, int e) : start(s), end(e) {}
};
class Solution {
public:
static bool mycomp(const Interval& l, const Interval& r) {
return (l.... | merge_intervals_new.cc | cc | 1,306 | en | cpp |
/*
* @lc app=leetcode.cn id=657 lang=cpp
*
* [657] 机器人能否返回原点
*/
#include <string>
using namespace std;
// @lc code=start
class Solution
{
public:
bool judgeCircle(string moves)
{
int arr[4] = {};
for (const char &cur : moves)
{
switch (cur)
{
ca... | 657.机器人能否返回原点.cpp | cpp | 710 | en | cpp |
#include <iostream>
#include <string>
#include <map>
using namespace std;
//在C++中字串的本質是由字元所組成的陣列,並在最後加上一個空(null)字元'\0'
class Solution {
public:
map<int, string>m[4];
Solution(){
m[0][1]="M";
m[1][1]="C";
m[2][1]="X";
m[3][1]="I";
m[1][5]="D";
m[2][5]="L";
m[3][5]="V";
for(int i=0;i<4... | integer_to_roman.cpp | cpp | 1,114 | en | cpp |
#include <bits/stdc++.h>
#include "mycommon.hpp"
using namespace std;
/** \brief hasCycle 环形链表
* \author wzk
* \copyright GNU Public License
* \version 1.0
* \date 2020-1-13
*
* \param[in] head 输入链表
* \return 返回是否有环
*/
bool hasCycle(ListNode *head) {
ListNode *fast = hea... | _6.cpp | cpp | 933 | en | cpp |
package array.bigestNumber;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Solution {
public static void main(String[] args) {
int[] arr = new int[]{3, 30, 34, 5, 9};
StringBuilder answer = new StringBuilder();
List<String> str = new ArrayList... | Solution.java | java | 637 | en | java |
""""""
"""
구현 문제였다
-- 좀 복잡하긴 했지만 잘 풀어낸 것 같다
"""
def solution(products, purchased):
# 1. 구매 물품 -- dict 자료형으로 만들기
dic = dict()
for string in products:
li = list(string.split())
dic[li.pop(0)] = li
# 2. 고객 구매 제품의 특성 dict 자료형으로 찾고 정렬하기
dic2 = dict()
for key in purchased:
... | problem2.py | py | 951 | ko | python |
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
var reduce = function(nums, fn, init) {
let acc = init;
for(const element of nums)
{
acc = fn(acc,element);
}
return acc;
};
| array-reduce-transform.js | js | 260 | en | javascript |
class Solution {
public:
void solve(int start,int k,int n,vector<bool> &inc,vector<int> &tillNow,vector<vector<int>> &ans){
if(k == 0 and n == 0){
ans.push_back(tillNow);
return;
}
else if(k == 0){
return;
}
for(int i = start;i<=9;i++){
... | 216-combination-sum-iii.cpp | cpp | 778 | en | cpp |
/*************************************************************************
> File Name: 3.LeetCode5602.cpp
> Author:赵睿
> Mail: 1767153298@qq.com
> Created Time: 2020年11月15日 星期日 10时52分10秒
************************************************************************/
#include<iostream>
#include<string>
#include<vector>... | 3.LeetCode5602.cpp | cpp | 1,334 | zh | cpp |
//78.Subsets
//Ques) array of unique elements,return all possible subsets (the power set).The solution set must not contain duplicate subsets. Return the solution in any order.
//ITERATIVE APPROACH
//ITERATIVE APPROACH (prakash shukla)
class Solution
{
public:
/*
//****************CONCEPT***********... | leetcode78.cpp | cpp | 4,535 | en | cpp |
// Solution 1:
// T[i][0] = max(T[i - 1][0], T[i - 1][1] + price);
// T[i][1] = max(T[i - 1][0] - price - fee, T[i - 1][1]);
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int presell = 0, sell = 0, buy = INT_MIN;
for (auto price : prices) {
presell = sell;
... | 714_best_time_to_buy_and_sell_stock_with_transaction_fee.cpp | cpp | 447 | en | cpp |
package com.leetcode.example.tree;
import com.leetcode.statics.model.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
public class _700_SearchInBinarySearchTree {
public static void main(String[] args) {
_700_SearchInBinarySearchTree c = new _700_SearchInBinarySearchTree();
c.start(... | _700_SearchInBinarySearchTree.java | java | 1,385 | en | java |
class Solution{
public:
//Function to find if there exists a triplet in the
//array A[] which sums up to X.
bool find3Numbers(int A[], int n, int X)
{
int a[100001];
for(int i=0;i<100001;i++){
a[i]=0;
}
for(int i=0;i<n;i++){
a[A[i]]++;
}
for(i... | Triplet_Sum_In_Array.cpp | cpp | 642 | en | cpp |
package DataWhale.Leetcode;
/**
* Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes
* that can be built with those letters.
* This is case sensitive, for example "Aa" is not considered a palindrome here.
* <p>
* Note:
* Assume the length of given ... | _0409_LongestPalindrome.java | java | 990 | en | java |
package linkedlist;
import java.util.ArrayList;
import java.util.List;
class Solution43 {
public static void main(String[] args) {
ListNode node = new ListNode(1);
node.add(new ListNode(2)).add(new ListNode(3)).add(new ListNode(4)).add(new ListNode(5)).add(null);
new Solution43().reverseLi... | Solution43.java | java | 1,721 | en | java |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
from typing import List
class Solution:
def allStar(self, s) -> bool:
if s == "":
return False
for i in s:
if i != "*":
return False
return True
def countQuestion(self, s:str)->List[int]:
head =... | 44_is_match.py | py | 3,297 | en | python |
/*
* Given a linked list, reverse the nodes of a linked list k at a time and
* return its modified list.
*
* If the number of nodes is not a multiple of k then left-out nodes in the end
* should remain as it is.
*
* You may not alter the values in the nodes, only nodes itself may be changed.
*
* Only constant ... | reverseKGroupNodes.cpp | cpp | 2,118 | en | cpp |
package com.chin._05._989;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class _989_add_to_array_form_of_integer {
public List<Integer> addToArrayForm(int[] num, int k) {
List<Integer> res = new ArrayList<>();
int len = num.length - 1;
int carry = ... | _989_add_to_array_form_of_integer.java | java | 1,149 | zh | java |
package string;
/**
* 459. Repeated Substring Pattern
* <p>
* Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
... | RepeatedSubstringPattern.java | java | 2,260 | en | java |
class Solution {
public:
int minArray(vector<int>& numbers) {
int len=numbers.size();
if(len<1) return -1;
int left=0,right=len-1;
if(numbers[left]<numbers[right]) return numbers[left];
while(right-left>1)
{
int middle=(left+right)/2;
if(number... | 面试题11. 旋转数组的最小数字.cpp | cpp | 563 | en | cpp |
# GROUP BY 절은 데이터들을 원하는 그룹으로 나눌 수 있다.
SELECT
Department.name AS 'Department',
Employee.name AS 'Employee',
Salary
FROM
Employee
JOIN
Department ON Employee.DepartmentId = Department.Id
WHERE
(Employee.DepartmentId , Salary) IN
( SELECT
DepartmentId, MAX(Salary)
... | DepartmentHighestSalary.sql | sql | 418 | en | sql |
#include <vector>
#include <iostream>
class MinStack {
public:
MinStack() {
}
MinStack(std::vector<int> input) {
for(auto i : input){
if(minimum.empty() || i <= getMin()){
minimum.push_back(i);
}
myStack.push_back(i);
}
}
... | Q6_MinStack.cpp | cpp | 1,020 | en | cpp |
/*
Date: 2023-11-29
ProblemID: 2336
ProblemName: 无限集中的最小数字
*/
package leetcode
type SmallestInfiniteSet struct {
Arr [1001]int
}
func Constructor() SmallestInfiniteSet {
arr := new(SmallestInfiniteSet)
for i := range arr.Arr {
arr.Arr[i] = 1
}
return *arr
}
func (this *SmallestInfiniteSet) PopSmallest() int {... | smallest-number-in-infinite-set.go | go | 690 | en | go |
function dailyTemperatures(T) {
const result = [];
for (let i = 0; i < T.length; i++) {
result[i] = 0;
const currentTemperature = T[i];
for (let j = i + 1; j < T.length; j++) {
if (T[j] > currentTemperature) {
result[i] = j - i;
break;
}
}
}
return result;
}
funct... | 0739_daily_temperatures.js | js | 777 | en | javascript |
package com.javarush.task.task18.task1821;
import java.io.FileReader;
import java.io.IOException;
public class Solution {
public static void main(String[] args) throws IOException {
int[] symbols = new int[256];
try (FileReader fileReader = new FileReader(args[0])) {
while (fileReader... | Solution.java | java | 623 | en | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.