Dataset Viewer (First 5GB)
Auto-converted to Parquet Duplicate
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*sizeof(int)); while(i < numsSize - 1 && numsSize > 1) { while(j < numsSize) { if(nums[i] + nums[j] == target && i != j) { array[0] = i; array[1] = j; return(array); } j++; } j = i + 1; i++; } return(0); }
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 *next) : val(x), next(next) {} * }; */ class Compare { public: bool operator()(ListNode* x, ListNode* y) { return x->val > y->val; } }; class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { int k = lists.size(); ListNode* result = new ListNode(); ListNode* temp = result; priority_queue<ListNode*, vector<ListNode*>, Compare> pq;//min heap for (int i = 0; i < k; i++) { if (lists[i] != NULL) { pq.push(lists[i]); } } while (!pq.empty()) { ListNode* t = pq.top(); pq.pop(); temp->next = t; temp = temp->next; t = t->next; if (t != NULL) { pq.push(t); } } return result->next; } };
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, func(i, j int) bool { if data[i][1] == data[j][1] { return data[i][0] > data[j][0] } return data[i][1] > data[j][1] }) res := make([]int, len(data)) for i, s := range data { res[i] = s[0] } return res }
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==0 and size == needleSize: return 0 if needleSize == 0 and size != 0: return 0 while idx<size: if haystack[idx] == needle[needlePos]: flag = 0 needleIdx = idx #print("idx",idx,needlePos,idx+needleSize-2,size) needlePos +=1 idx1= idx+1 # print("idx",idx1,needlePos,idx+needleSize-2,size) if (idx1+needleSize-2) < size: #print("gere") while needlePos<needleSize: if haystack[idx1] == needle[needlePos]: print(haystack[idx1],idx1,needlePos) idx1+=1 needlePos+=1 else: flag = 1 break if flag==0: return needleIdx needlePos = 0 idx+=1 needleIdx = -1 return needleIdx #optimized class Solution: def strStr(self, haystack: str, needle: str) -> int: needleIdx = -1 idx = 0 needlePos = 0 size = len(haystack) needleSize = len(needle) if needleSize==0 and size == needleSize: return 0 if needleSize == 0 and size != 0: return 0 if size<needleSize: return -1 while idx<size: if haystack[idx:idx+needleSize] == needle: return idx idx+=1 return needleIdx
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 } val node1 = nullNode.next(k - 1) var node2: ListNode? = nullNode var current: ListNode? = nullNode.next(k + 1) while (current != null) { current = current.next node2 = node2?.next } if (node1 != node2) { swapLinks(node1, node2) swapLinks(node1?.next, node2?.next) } return nullNode.next } private fun swapLinks(node1: ListNode?, node2: ListNode?) { val temp = node1?.next node1?.next = node2?.next node2?.next = temp } private fun ListNode?.next(skip: Int): ListNode? { var listNode: ListNode? = this for (i in 0 until skip) { listNode = listNode?.next } return listNode } }
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 res=0; for( int i = 0 ; i < stoneValue.size() ; ++i ){ res = max(perm(stoneValue,0,i,stoneValue.size()),res); } return res; } int perm(vector<int>& stoneValue,int s, int mid, int e){ int sum_a = 0; for( int i = s ; i < mid ; ++i ){ sum_a += stoneValue[i]; } int sum_b = 0; for( int i = mid ; i < e ; ++i ){ sum_b += stoneValue[i]; } int res = 0; //cout << "sum:" << sum_a << "," << sum_b << "idx" << s << "," << mid << "," << endl; if ( sum_a > sum_b || sum_a == sum_b ) { for( int i = mid ; i < e ; ++i ){ res = max( sum_b + perm(stoneValue,mid,i,e), res ); } } if( sum_a < sum_b || sum_a == sum_b ) {// 0 1 2 for( int i = s ; i < mid ; ++i ){ res = max( sum_a + perm(stoneValue,s,i,mid), res ); } } return res; } }; int main() { vector<int> i1{6,2,3,4,5,5}; auto s = new Solution(); cout << s->stoneGameV(i1) << endl; vector<int> i2{7,7,7,7,7,7,7}; cout << s->stoneGameV(i2) << endl; vector<int> i3{1,1,2}; cout << s->stoneGameV(i3) << endl; }
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 [] elementRow = new int[sizeR]; int [] frequencyRow = new int[sizeR]; int fSum = 0; for(int i = 0; i < sizeR; i++){ elementRow[i] = ui.nextInt(); } for (int i = 0; i < sizeR; i++){ frequencyRow[i] = ui.nextInt(); fSum = fSum + frequencyRow[i]; } ArrayList<Integer> dataSet = new ArrayList<>(); for (int i = 0; i < frequencyRow.length; i++){ for (int j = 0; j < frequencyRow[i]; j++){ dataSet.add(elementRow[i]); } } Collections.sort(dataSet); System.out.println(dataSet.toString()); } }
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([]) nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] for i in range(len(board)): for j in range(len(board[0])): if board[i][j] != '.': rows[i].add(board[i][j]) cols[j].add(board[i][j]) boxes[(i // 3)*3 + j // 3].add(board[i][j]) else: seen.append((i, j)) def search(): if not seen: return True r, c = seen[0] box = (r // 3)*3 + c // 3 for num in nums: if num not in rows[r] and num not in cols[c] and num not in boxes[box]: board[r][c] = num rows[r].add(num) cols[c].add(num) boxes[box].add(num) seen.popleft() if search(): return True else: board[r][c] = '.' rows[r].discard(num) cols[c].discard(num) boxes[box].discard(num) seen.appendleft((r, c)) return False search()
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] Output: false Example 3: Input: [1,1,1,3,3,4,3,2,4,2] Output: true */ // sort and compare func containsDuplicate(nums []int) bool { sort.Ints(nums) for i := 1; i < len(nums); i++ { if nums[i] == nums[i-1] { return true } } return false } // use hash map func containsDuplicateByHashMap(nums []int) bool { m := make(map[int]bool) for _, v := range nums { if _, ok := m[v]; ok { return true } else { m[v] = true } } return false }
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 different representation public int reverseBits_2(int n) { int res = 0; for (int i = 0; i < 32; i++) { res += n & 1;// get the most right bit each time n >>>= 1;// do UN-signed right shift by 1 each time if (i < 31) { res <<= 1;// shift this number to the left by 1 each time, so that eventually, this number // is reversed } } return res; } }
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][y] = ways(x+1,y,dp,m,n) + ways(x,y+1,dp,m,n); } int uniquePaths(int m, int n) { vector<vector<int>> dp(m,vector<int> (n,-1)); // dp[i][j] -> no of ways to reach m-1,n-1 from i,j return ways(0,0,dp,m,n); } }; // O(MIN(r,c)) time and O(1) space class Solution { public: int uniquePaths(int r, int c) { int n = r-1,m=c-1; // ans = (n+m)cn/m int s=n+m; n=min(n,m); // ans=scn if(n==0){ return 1; } long long int ans=1; for(int i=1;i<=n;i++){ ans=ans*(s-i+1); ans=ans/i; } return ans; } };
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 lenA > lenB: headA = self.moveForward(headA, lenA - lenB) else: headB = self.moveForward(headB, lenB - lenA) # 将两个头向前移动,直到它们相交 while headA and headB: if headA == headB: return headA headA = headA.next headB = headB.next return None def getLength(self, head: ListNode) -> int: length = 0 while head: length += 1 head = head.next return length def moveForward(self, head: ListNode, steps: int) -> ListNode: while steps > 0: head = head.next steps -= 1 return head class Solution2: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: if not headA or not headB: return None nodeA = headA nodeB = headB while(nodeA !=nodeB): nodeA = nodeA.next if nodeA else headB nodeB = nodeB.next if nodeB else headA return nodeA # https://leetcode.cn/problems/intersection-of-two-linked-lists/solution/jiao-ni-yong-lang-man-de-fang-shi-zhao-dao-liang-2/
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 jobScheduling(int[] startTime, int[] endTime, int[] profit) { int n = startTime.length; var sorted = new int[n][3]; for (int i = 0; i < n; i++) { sorted[i] = new int[]{startTime[i], endTime[i], profit[i]}; } Arrays.sort(sorted, (a, b) -> a[1] - b[1]); TreeMap<Integer,Integer> f = new TreeMap<>(); int max = 0; for (int i = 0; i < n; i++) { int end = sorted[i][1],start = sorted[i][0]; var floorEntry = f.floorEntry(start); int floorValue = floorEntry == null ? 0 : floorEntry.getValue(); //max 为[0,end]的最大值 max = Math.max(max,floorValue + sorted[i][2]); f.put(end,max); } return max; } public static void main(String[] args) { JobScheduling1235 jobScheduling = new JobScheduling1235(); System.out.println(jobScheduling.jobScheduling(TransformUtil.toIntArray("[4,2,4,8,2]"), TransformUtil.toIntArray("[5,5,5,10,8]"), TransformUtil.toIntArray("[1,2,8,10,4]"))); System.out.println(jobScheduling.jobScheduling(TransformUtil.toIntArray("[4,2,4,8,2]"), TransformUtil.toIntArray("[5,5,5,10,8]"), TransformUtil.toIntArray("[1,2,8,10,4]")) == 18); } }
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[i] <= nums.size()) vec[nums[i]] = true; for(int i = 1; i < vec.size(); i++) if(vec[i] == false) result.push_back(i); return result; } };
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) return ballot.get(0); Map<String, Integer> vote = new HashMap<String, Integer>(); // Initialize Map with candidate name and number of vote for (int i = 0; i <= ballot.size(); i++) { if (vote.containsKey(ballot.get(i))) { vote.put(ballot.get(i), vote.get(ballot.get(i))+1); } else { vote.put(ballot.get(i), 1); } } //Find candidates with highest vote int highest = 0; for (Map.Entry<String, Integer> e : vote.entrySet()) { System.out.println("Key = " + e.getKey() + ", Value = " + e.getValue()); if (e.getValue() > highest){ highest = e.getValue(); } } // Analyze candidates with highest vote List<String> list=new ArrayList<String>(); for (Map.Entry<String, Integer> e : vote.entrySet()) { if (e.getValue() == highest){ list.add(e.getKey()); } } String winner = list.get(0); if (list.size() == 1) return list.get(0); else { for (int i = 1; i < list.size(); i++) { if (list.get(i).compareToIgnoreCase(winner) > 0){ winner = list.get(i); } } } return winner; } }
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 col[y] || diag1[d1] || diag2[d2] { continue } col[y] = true diag1[d1] = true diag2[d2] = true dfs(append(q, y)) col[y] = false diag1[d1] = false diag2[d2] = false } } dfs(make([]int, 0, n)) return } func main() { var n int n = 4 fmt.Println(n, totalNQueens(n)) }
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 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ object FindMedianSortedArrays extends App { def findMedianSortedArrays1(nums1: Array[Int], nums2: Array[Int]): Double = { val length = nums1.length + nums2.length var array1Index = 0 var array2Index = 0 val newArray = new Array[Int](length / 2 + 1) while (array1Index != nums1.length && array2Index != nums2.length && (array1Index + array2Index) <= length / 2) { if (nums1(array1Index) < nums2(array2Index)) { newArray(array1Index + array2Index) = nums1(array1Index) array1Index += 1 } else { newArray(array1Index + array2Index) = nums2(array2Index) array2Index += 1 } } while ((array1Index + array2Index) <= length / 2) { if (array1Index != nums1.length) { newArray(array1Index + array2Index) = nums1(array1Index) array1Index += 1 } else { newArray(array1Index + array2Index) = nums2(array2Index) array2Index += 1 } } if (length % 2 == 0) { (newArray(length / 2) + newArray(length / 2 - 1)).toDouble / 2 } else { newArray(length / 2).toDouble } } def findMedianSortedArrays2(nums1: Array[Int], nums2: Array[Int]): Double = { val (shortArray, longArray) = { if (nums1.length < nums2.length) (nums1, nums2) else (nums2, nums1) } val shortLength = shortArray.length val longLength = longArray.length if (shortLength == 0) (longArray((longLength + 1) / 2 - 1) + longArray((longLength + 2) / 2 - 1)).toDouble / 2 else { var indexLeft = 1 var indexRight = shortLength val halfLength = (shortLength + longLength + 1) / 2 var result = 0.0 while (indexLeft <= indexRight) { val shortMedian = (indexLeft + indexRight) / 2 val longMedian = halfLength - shortMedian if (shortMedian > indexLeft && shortArray(shortMedian - 1) > longArray(longMedian)) { indexRight = shortMedian - 1 } else if (shortMedian < indexRight && shortArray(shortMedian) < longArray(longMedian - 1)) { indexLeft = shortMedian + 1 } else { val maxLeft = { if(shortMedian == 0) longArray(longMedian) else if(longMedian == 0) shortArray(shortMedian -1) else if (shortArray(shortMedian - 1) > longArray(longMedian - 1)) shortArray(shortMedian - 1) else longArray(longMedian - 1) } if ((shortLength + longLength).&(1) != 0) { result = maxLeft } else { val minRight = { if (shortMedian == shortLength) longArray(longMedian) else if (longMedian == longLength) shortArray(shortMedian) else if (shortArray(shortMedian) > longArray(longMedian)) longArray(longMedian) else shortArray(shortMedian) } result = (maxLeft + minRight).toDouble / 2 } indexLeft = indexLeft + 1 } } result } } println(findMedianSortedArrays1(Array(1, 3), Array(2))) println(findMedianSortedArrays1(Array(1, 2), Array(3, 4))) println(findMedianSortedArrays1(Array(1, 2), Array())) println(findMedianSortedArrays2(Array(1, 3), Array(2))) println(findMedianSortedArrays2(Array(1, 2), Array(3, 4))) println(findMedianSortedArrays2(Array(1, 2), Array())) }
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. */ public class Intersection_of_Two_Arrays { /* Time complexity, O(M+N)*/ public int[] intersection(int[] nums1, int[] nums2) { /* set_nums stores a set of elements in nums1, while result stores the return elements, so ensure uniqueness */ HashSet<Integer> set_Nums = new HashSet<>(); HashSet<Integer> result = new HashSet<>(); /* add all elements in nums1 in set_nums */ for(int i:nums1) set_Nums.add(i); /* Iterate through nums2, if the elements already in the set, put it the result set */ for(int i:nums2){ if(set_Nums.contains(i)){ result.add(i); } } int size = result.size(); int intersection[] = new int[size]; int k=0; for(int value:result){ intersection[k++]=value; } return intersection; } public static void main(String[] args){ int[] nums1={1}; int[] nums2={1,1}; int[] result = new Intersection_of_Two_Arrays().intersection(nums1,nums2); for(int i:result){ System.out.print(i+" "); } } }
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) { break; } } } int ans=0; for(int i=0;i<n;i++) { if(v[i]==k) break; ans++; } cout<<ans<<endl; }
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 { public static int maxSubArray(int[] nums) { if(null == nums || 0 == nums.length){ throw new RuntimeException(); } int max = nums[0]; int start = 0; int end = start; int sum = 0; for(int i = 0; i< nums.length;i++){ sum = 0; for(int j=i; j< nums.length;j++){ sum += nums[j]; if(sum > max){ max = sum; start = i; end = j; } } } System.out.println("start:" + start + " end:" + end); return max; } /** * discuss answer * @param nums * @return */ public static int maxSubArray2(int[] nums) { int max = Integer.MIN_VALUE, sum = 0; for (int i = 0; i < nums.length; i++) { if (sum < 0) { sum = nums[i]; } else { sum += nums[i]; } if (sum > max) { max = sum; } } return max; } public static void main(String[] args) { System.out.println(maxSubArray(new int[]{-2,1,-3,4,-1,2,1,-5,4})); System.out.println(maxSubArray(new int[]{-2,1})); } }
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: return [] s1 = [root] s2 = [] level = [] result = [] while s1 or s2: while s1: node = s1.pop() level.append(node.val) if node.left: s2.append(node.left) if node.right: s2.append(node.right) if level: result.append(level) level = [] while s2: node = s2.pop() level.append(node.val) if node.right: s1.append(node.right) if node.left: s1.append(node.left) if level: result.append(level) level = [] return result
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<int>& speed) { vector<vector<float>> fleet; } }; int main(){ return 0; }
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); return shortUrl; } // Decodes a shortened URL to its original URL. public String decode(String shortUrl) { return map.get(shortUrl.hashCode()); } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.decode(codec.encode(url));
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 head, int k) { if(head == null || head.next == null){ return head; } ListNode temp = head; // FINDING SIZE int size = 0; while(temp!=null){ temp = temp.next; size++; } // FINDING REAR ListNode rear =head; for(int i = 1; i < size;i++){ rear = rear.next; } // ROTATING THE LINKEDLIST int r = k%size; int nr = size-r-1; ListNode rot = head; for(int i=0;i<nr;i++){ rot = rot.next; } rear.next = head; head = rot.next; rot.next = null; return head; } }
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) { dp[i] = vector<int>(n, 0x3f3f3f3f); } dp[0][0] = grid[0][0]; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { // move right if (j + 1 < n) { dp[i][j + 1] = min(dp[i][j + 1], dp[i][j] + grid[i][j + 1]); } // move down if (i + 1 < m) { dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + grid[i + 1][j]); } } } return dp[m - 1][n - 1]; } };
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 //the previous n-2 is abandoned public int climbStairs(int n) { if(n==0||n==1||n==2) return n; int one_step=2; int two_step=1; int sum = 0; for(int i = 2; i < n; i++){ sum = one_step+two_step; two_step=one_step; one_step=sum; } return sum; } long method = 0; public long RC(int n){ method=0; int sum =0; rec(sum,n); return method; } public void rec(int sum, int n){ if(sum+2<n){ sum+=1; rec(sum,n); sum+=1; rec(sum,n); }else if(sum+2==n){ method+=2; }else if(sum+1==n){ method++; } } public static void main(String[] args){ Q070 instance = new Q070(); int num = 46; System.out.println(instance.RC(num)); System.out.println(instance.climbStairs(num)); } }
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; } i++; } } };
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 += 1; if (count === k) { return cur; } } return -1; } console.log(findKthPositive([2, 3, 4, 7, 11], 5)); console.log(findKthPositive([1, 2, 3, 4], 2));
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>&nbsp;</p> * * <p><strong>示例:</strong></p> * * <pre>给定 <code>1-&gt;2-&gt;3-&gt;4</code>, 你应该返回 <code>2-&gt;1-&gt;4-&gt;3</code>. * </pre> * * * @author Leammin * @date 2021-04-03 */ public interface SwapNodesInPairs { ListNode swapPairs(ListNode head); class Solution implements SwapNodesInPairs { @Override public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) { return head; } ListNode newHead = head.next; head.next = newHead.next; newHead.next = head; ListNode node = head; while (node.next != null && node.next.next != null) { ListNode a = node.next; ListNode b = a.next; ListNode c = b.next; node.next = b; b.next = a; a.next = c; node = a; } return newHead; } } }
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 else: return t return -1 print(Solution().search([1,2,3,4,5,6,7,8], 8))
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) { return true; } char[] chars = s.toCharArray(); int l = 0, r = chars.length - 1; while (l < r) { if (!Character.isLetterOrDigit(chars[l])) { l++; continue; } if (!Character.isLetterOrDigit(chars[r])) { r--; continue; } if (Character.toLowerCase(chars[l++]) != Character.toLowerCase(chars[r--])) { return false; } } return true; } }
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(Node node){ if(node==null) return; System.out.println(node.value); preOrder(node.left); preOrder(node.right); } public static void iterPreOrder(Node node){ Stack<Node> stack = new Stack<>(); stack.push(node); while(!stack.isEmpty()){ Node temp = stack.pop(); if(temp.right!=null) stack.push(temp.right); if(temp.left!=null) stack.push(temp.left); System.out.println(temp.value); } } public static void iterInOrder(Node node){ Stack<Node> stack = new Stack<>(); while(true){ if(node!=null) { stack.push(node); node=node.left; }else{ if(!stack.isEmpty()){ node=stack.pop(); System.out.println(node.value); node=node.right; }else{ break; } } } } public static void inOrder(Node node){ if(node==null) return; inOrder(node.left); System.out.println(node.value); inOrder(node.right); } public static void postOrder(Node node){ if(node==null) return; postOrder(node.left); postOrder(node.right); System.out.println(node.value); } public static void iterPostOrder(Node node){ Stack<Node> stack = new Stack<>(); Stack<Node> stack2 = new Stack<>(); if(node==null) return; stack.push(node); while(!stack.isEmpty()){ Node temp = stack.pop(); stack2.push(temp); if(temp.left!=null) stack.push(temp.left); if(temp.right!=null) stack.push(temp.right); } while(!stack2.isEmpty()){ System.out.println(stack2.pop().value); } } public static void levelOrder(Node node){ Queue<Node> queue = new LinkedList<>(); queue.offer(node); while(!queue.isEmpty()){ if(queue.peek().left!=null){ queue.add(queue.peek().left); } if(queue.peek().right!=null){ queue.add(queue.peek().right); } System.out.println(queue.poll().value); } } public static void morrisPreOrder(Node node){ if(node==null) return; Node curr = node; while(curr!=null){ if(curr.left==null){ System.out.println(curr.value); curr=curr.right; }else{ Node temp = curr.left; while(temp.right!=null && temp.right!=curr){ temp = temp.right; } if(temp.right==null){ temp.right=curr; System.out.println(curr.value); curr=curr.left; }else{ temp.right=null; curr=curr.right; } } } } }
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(TreeNode root) { if (root == null) return root; TreeNode tmpNode = root.left; root.left = root.right; root.right = tmpNode; invertTree(root.left); invertTree(root.right); return root; } }
_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.size()-1;i>=0;i--){ pdt=pdt*nums[i]; maxi=max(pdt,maxi); if(pdt==0){ pdt=1; } } return maxi; } };
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 island. Return the maximum area of an island in grid. If there is no island, return 0. Example 1: Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]] Output: 6 Explanation: The answer is not 11, because the island must be connected 4-directionally. Example 2: Input: grid = [[0,0,0,0,0,0,0,0]] Output: 0 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 50 grid[i][j] is either 0 or 1. """ # V0 # IDEA : DFS # * PLEASE NOTE THAT IT IS NEEDED TO GO THROUGH EVERY ELEMENT IN THE GRID # AND RUN THE DFS WITH IN THIS PROBLEM class Solution(object): def maxAreaOfIsland(self, grid): """ :type grid: List[List[int]] :rtype: int """ self.res = 0 self.island = 0 M, N = len(grid), len(grid[0]) for i in range(M): for j in range(N): if grid[i][j]: self.dfs(grid, i, j) self.res = max(self.res, self.island) self.island = 0 return self.res def dfs(self, grid, i, j): # ensure grid[i][j] == 1 M, N = len(grid), len(grid[0]) grid[i][j] = 0 self.island += 1 dirs = [(0, 1), (0, -1), (-1, 0), (1, 0)] for d in dirs: x, y = i + d[0], j + d[1] if 0 <= x < M and 0 <= y < N and grid[x][y]: self.dfs(grid, x, y) # V1 # https://blog.csdn.net/fuxuemingzhu/article/details/79182435 # IDEA : DFS # * PLEASE NOTE THAT IT IS NEEDED TO GO THROUGH EVERY ELEMENT IN THE GRID # AND RUN THE DFS WITH IN THIS PROBLEM class Solution(object): def maxAreaOfIsland(self, grid): """ :type grid: List[List[int]] :rtype: int """ self.res = 0 self.island = 0 M, N = len(grid), len(grid[0]) for i in range(M): for j in range(N): if grid[i][j]: self.dfs(grid, i, j) self.res = max(self.res, self.island) self.island = 0 return self.res def dfs(self, grid, i, j): # ensure grid[i][j] == 1 M, N = len(grid), len(grid[0]) grid[i][j] = 0 self.island += 1 dirs = [(0, 1), (0, -1), (-1, 0), (1, 0)] for d in dirs: x, y = i + d[0], j + d[1] if 0 <= x < M and 0 <= y < N and grid[x][y]: self.dfs(grid, x, y) # V1' # https://blog.csdn.net/fuxuemingzhu/article/details/79182435 # IDEA : DFS class Solution(object): def maxAreaOfIsland(self, grid): """ :type grid: List[List[int]] :rtype: int """ row, col = len(grid), len(grid[0]) answer = 0 def dfs(i, j): if 0 <= i <= row - 1 and 0 <= j <= col - 1 and grid[i][j]: grid[i][j] = 0 return 1 + dfs(i - 1, j) + dfs(i + 1, j) + dfs(i, j - 1) + dfs(i, j + 1) return 0 return max(dfs(i, j) for i in range(row) for j in range(col)) # V1'' # https://blog.csdn.net/fuxuemingzhu/article/details/79182435 # IDEA : BFS # DEV # V1''' # https://www.jiuzhang.com/solution/max-area-of-island/#tag-highlight-lang-python # IDEA : DFS class Solution(object): def maxAreaOfIsland(self, grid): """ :type grid: List[List[int]] :rtype: int GET EACH ISLAND AREA VIA DFS """ if not grid: return rows, cols = len(grid), len(grid[0]) max_area = -sys.maxint - 1 for i in range(rows): for j in range(cols): if grid[i][j] == 1: max_area = max(max_area,self.doDfs(grid,i,j,1)) return max(0,max_area) def doDfs(self,grid,i,j,count): grid[i][j] = 0 for m,n in [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]: if(m>=0 and m<len(grid) and n>=0 and n<len(grid[0]) and grid[m][n] == 1): count = 1 + self.doDfs(grid,m,n,count) return count # V2 # Time: O(m * n) # Space: O(m * n), the max depth of dfs may be m * n class Solution(object): def maxAreaOfIsland(self, grid): """ :type grid: List[List[int]] :rtype: int """ directions = [[-1, 0], [ 1, 0], [ 0, 1], [ 0, -1]] def dfs(i, j, grid, area): if not (0 <= i < len(grid) and \ 0 <= j < len(grid[0]) and \ grid[i][j] > 0): return False grid[i][j] *= -1 area[0] += 1 for d in directions: dfs(i+d[0], j+d[1], grid, area) return True result = 0 for i in range(len(grid)): for j in range(len(grid[0])): area = [0] if dfs(i, j, grid, area): result = max(result, area[0]) return result
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) { int result = 0; for (int c = 0; c < arr[0].length(); ++c) { for (int r = 0; r < arr.length - 1; ++r) { if (arr[r].charAt(c) > arr[r + 1].charAt(c)) { result++; break; } } } return result; } }
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]' * * 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。 * * 最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。 * * 你可以假设除了整数 0 之外,这个整数不会以零开头。 * * 示例 1: * * 输入: [1,2,3] * 输出: [1,2,4] * 解释: 输入数组表示数字 123。 * * * 示例 2: * * 输入: [4,3,2,1] * 输出: [4,3,2,2] * 解释: 输入数组表示数字 4321。 * * */ /** * @param {number[]} digits * @return {number[]} */ function sumStrings(a, b) { var res = "", c = 0; a = a; b = b.split(""); while (a.length || b.length || c) { c += ~~a.pop() + ~~b.pop(); res = (c % 10) + res; c = c > 9; } return res.replace(/^0+/, ""); } var plusOne = function(digits) { var num = sumStrings(digits, "1"); return (num + "").split(""); }; console.log(plusOne([6, 1, 4, 5, 3, 9, 0, 1, 9, 5, 1, 8, 6, 7, 0, 5, 5, 4, 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++) { for (int j = 0; j <= i - 1; j++) { dp[i] += dp[i - j - 1] * dp[j]; } } return dp[n]; } }
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 first and the only argument is an array of integers, A. Output Format: Return an integer, representing the maximum possible profit. */ // Time Complexity - O(N) // Space Complexity - O(N) import java.util.List; class Solution { public int maxProfit(final List<Integer> A) { if (A.isEmpty()) return 0; int[] minValue = new int[A.size()]; minValue[0] = A.get(0); for (int i = 1; i < A.size(); i++) minValue[i] = Math.min(minValue[i - 1], A.get(i)); int maxProfit = 0; for (int i = 0; i < A.size(); i++) { maxProfit = Math.max(maxProfit, A.get(i) - minValue[i]); } return maxProfit; } }
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>(); helper(s,0,item,res); return res; } private void helper(String s,int start,ArrayList<String> item,ArrayList<ArrayList<String>> res){ if(start==s.length()){ res.add(new ArrayList<String>(item)); return; } for(int i=start;i<s.length();i++){ String str = s.substring(start,i+1); if(isPalindrome(str)){ item.add(str); helper(s,i+1,item,res); item.remove(item.size()-1); } } } public boolean isPalindrome(String s){ int low=0; int high=s.length()-1; while(low<high){ if(s.charAt(low)!=s.charAt(high)){ return false; } low++; high--; } return true; } /* public ArrayList<ArrayList<String>> partition(String s) { ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>(); if(s==null||s.length()==0){ return result; } ArrayList<String> partition = new ArrayList<String>(); helper(s,getDict(s),0,partition,result); return result; } private void helper(String s, boolean [][]dict,int start,ArrayList<String> partition,ArrayList<ArrayList<String>> result){ if(start==s.length()){ ArrayList<String> temp = new ArrayList<String>(partition); result.add(temp); return; } for(int i=start;i<s.length();i++){ if(dict[start][i]){ partition.add(s.substring(start,i+1)); helper(s,dict,i+1,partition,result); partition.remove(partition.size()-1); } } } private boolean[][] getDict(String str){ boolean[][] dict= new boolean [str.length()][str.length()]; for(int i = str.length()-1;i>=0;i--){ for(int j=i;j<str.length();j++){ if(str.charAt(i)==str.charAt(j)&& ((j-i<2)||dict[i+1][j-1])){ dict[i][j]=true; } } } return dict; }*/ }
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] 放数组里 * 然后循环往复这个过程,最终要得到的一块石头的重量最小 * * 我是真没看出来该使用动态规划的方式去求解 * 转化成动态规划的模型求解就是 * 石头分两堆 * 然后让两堆的重量尽量一致 * 模型就转换成背包重量是sum/2(我们假设所有石头的重量和是sum) * 然后我们往sum/2的包里放石头,尽量让石头最重 */ /** * 二维数组方式的动态规划,更利于理解,只不过添加了一个价值维度 * 在这个题里边,价值就是重量 * 于是我们定义dp数组 * dp[i][j] 表示 从0~i的下标中选石头向重量为j的包里装的最大价值 * * 状态转移 * dp[i][j] * 对于下标为i的石头 * 放 dp[i-1][j-w[i]] + value[i] => dp[i-1][j-stones[i]] + stones[i] * 不放 dp[i-1][j] * dp[i][j] = max(dp[i-1][j], dp[i-1][j-stones[i]] + stones[i]) * * 初始化 * dp[0][j]取下标为0的石头放包里,不是随便放的哦,必须满足stones[0]重量比包小才行 * 即 j = stones[0]开始 * * 对于dp[i][0] 包的大小为0,那么必然是dp[i][0] = 0; */ // const len = stones.length; // // 求和 // const sum = stones.reduce((pre, cur) => pre + cur); // // 分堆 // const bagSize = Math.floor(sum/2); // // 构造dp数组 // const dp = []; // for (let i = 0; i < len; i++) { // dp[i] = []; // for (let j = 0; j <= bagSize; j++) { // dp[i][j] = 0; // } // } // // 初始化 // // dp[i][0]的情况已经在构造dp数组的情况中完成了初始化 // // 初始化dp[0][i]的情况就好 // for (let i = stones[0]; i <= bagSize; i++) { // dp[0][i] = stones[0]; // } // // 开始遍历进行状态转移 // for (let i = 1; i < len; i++) { // 遍历石头 // for (let j = 1; j <= bagSize; j++) { // 遍历背包大小 // if (j < stones[i]) { // dp[i][j] = dp[i-1][j]; // } else { // dp[i][j] = Math.max(dp[i-1][j], dp[i-1][j-stones[i]] + stones[i]); // } // } // } // return (sum - dp[len-1][bagSize]) - dp[len-1][bagSize]; /** * 使用一维数组的方式 * 在二维数组的方式中,dp[i][j] = dp[i-1][j],我们可以节省掉这一步 * 一维数组的方式可能更简洁,但是略微难以理解 * * dp数组的定义 * dp[j]表示容积为j的背包装石头的最大价值为dp[j] * * 状态转移 * 从二维数组直接迁移过来 * dp[j] = max(dp[j], dp[j-stone[i]] + stones[i]) * * 初始化 * dp[0]背包的容积是0,那么必然是0 */ const len = stones.length; // 求和 const sum = stones.reduce((pre, cur) => pre + cur); // 分堆 const bagSize = Math.floor(sum/2); // 构造dp数组 const dp = new Array(bagSize + 1).fill(0); // 初始化 好像不用初始化了,在构造过程中已经完成了初始化 // 遍历 for (let i = 0; i < len; i++) { // 遍历石头 // for (let j = bagSize; j >= 0; j--) { // 遍历背包,需要从后向前哦 从后向前可以避免石头使用两次 // if (j >= stones[i]) { // dp[j] = Math.max(dp[j], dp[j-stones[i]] + stones[i]); // } // } for (let j = bagSize; j >= stones[i]; j--) { // 遍历背包,需要从后向前哦 从后向前可以避免石头使用两次 dp[j] = Math.max(dp[j], dp[j-stones[i]] + stones[i]); } } return (sum-dp[bagSize]) - dp[bagSize]; }; // @lc code=end
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, } } func Constructor(capacity int) LRUCache { first := newNode(0, 0) last := newNode(0, 0) first.next = last last.prev = first return LRUCache{ capacity: capacity, cacheMap: make(map[int]*Node), first: first, last: last, } } func (this *LRUCache) Get(key int) int { var res int if v, ok := this.cacheMap[key]; !ok { return -1 } else { this.remove(v) this.InsertFirst(v) res = v.val } return res } func (this *LRUCache) Put(key int, value int) { if v, ok := this.cacheMap[key]; ok { v.val = value if v != this.first.next { this.remove(v) this.InsertFirst(v) } } else { if len(this.cacheMap) == this.capacity { delete(this.cacheMap, this.last.prev.key) this.remove(this.last.prev) } node := newNode(key, value) this.cacheMap[key] = node this.InsertFirst(node) } } func (this *LRUCache) InsertFirst(node *Node) { node.next = this.first.next this.first.next = node node.prev = this.first node.next.prev = node } func (this *LRUCache) remove(node *Node) { node.next.prev = node.prev node.prev.next = node.next }
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 = sArrays[0].length(); char[][] map = new char[m][n];//存储m*n冰田块信息图 map[0] = sArrays[0].toCharArray(); for (int i = 1; i < m; i++) { sArrays[i] = in.nextLine(); map[i] = sArrays[i].toCharArray(); } boolean[][] isFind = new boolean[m][n];//存储对应map是否遍历 for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) isFind[i][j] = false; } int count = 0;//记录冰田区域数 for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (!isFind[i][j]) { if (map[i][j] == '*') { findMap(map, isFind, i, j, m, n); count++; } else isFind[i][j] = true; } } } System.out.println(String.valueOf(count)); } private static void findMap(char[][] map, boolean[][] isFind, int i, int j, int m, int n) { isFind[i][j] = true; //左上方 if (i > 0 && j > 0 && !isFind[i - 1][j - 1]) { if (map[i - 1][j - 1] == '*') findMap(map, isFind, i - 1, j - 1, m, n); } //上方 if (i > 0 && !isFind[i - 1][j]) { if (map[i - 1][j] == '*') findMap(map, isFind, i - 1, j, m, n); } //右上方 if (i > 0 && j < n - 1 && !isFind[i - 1][j + 1]) { if (map[i - 1][j + 1] == '*') findMap(map, isFind, i - 1, j + 1, m, n); } //左方 if (j > 0 && !isFind[i][j - 1]) { if (map[i][j - 1] == '*') findMap(map, isFind, i, j - 1, m, n); } //右方 if (j < n - 1 && !isFind[i][j + 1]) { if (map[i][j + 1] == '*') findMap(map, isFind, i, j + 1, m, n); } //右下方 if (i < m - 1 && j > 0 && !isFind[i + 1][j - 1]) { if (map[i + 1][j - 1] == '*') findMap(map, isFind, i + 1, j - 1, m, n); } //下方 if (i < m - 1 && !isFind[i + 1][j]) { if (map[i + 1][j] == '*') findMap(map, isFind, i + 1, j, m, n); } //右下方 if (i < m - 1 && j < n - 1 && !isFind[i + 1][j + 1]) { if (map[i + 1][j + 1] == '*') findMap(map, isFind, i + 1, j + 1, m, 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 val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } public class Add2Numbers_2 { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int sum = ((l1!=null?l1.val:0) + (l2!=null?l2.val : 0))%10; int l1Val = l1!=null?l1.val : 0; int l2Val = l2!=null?l2.val : 0; int rem = (l1Val + l2Val)/10; ListNode sumNode = new ListNode(sum); ListNode finalSumNode = sumNode; if(l1!=null) l1 = l1.next; if(l2!=null) l2 = l2.next; while(l1 != null || l2 != null || rem>0) { l1Val = l1!=null?l1.val : 0; l2Val = l2!=null?l2.val : 0; ListNode listNodeSum = new ListNode((l1Val + l2Val + rem)%10); sumNode.next = listNodeSum; sumNode = sumNode.next; rem = (l1Val + l2Val + rem)/10; l1 = l1!=null?l1.next:null; l2 = l2!=null?l2.next:null; } return finalSumNode; } public void print(ListNode listNode) { while(listNode!=null) { System.out.println(listNode.val); listNode = listNode.next; } } }
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) { PriorityQueue<int[]> queue = new PriorityQueue<>( (a,b) -> b[1] - a[1] ) ; queue.addAll(Arrays.asList(boxTypes)) ; int unitCount = 0 ; while (!queue.isEmpty()) { int[] top = queue.poll() ; int boxCount = Math.min(top[0], truckSize) ; unitCount += boxCount * top[1] ; truckSize -= boxCount ; if(truckSize == 0) { break; } } return unitCount ; } }
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 while l1 or l2: x = l1.val if l1 else 0 y = l2.val if l2 else 0 tmp = (x+y+add)%10 add = (x+y+add)//10 cur.next = ListNode(tmp) if l1: l1 = l1.next if l2: l2 = l2.next cur = cur.next if add > 0: cur.next = ListNode(add) return dummy.next c=ListNode(2) d=ListNode(3) e=ListNode(6) c.next=d d.next=e f=ListNode(9) g=ListNode(5) f.next=g a=Solution() res=a.addTwoNumbers(c,f) t=[] while res: t.append(res.val) res=res.next print(t)
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()) { hash[str].push_back(strs[i]); } else { vector<string> value_str; value_str.push_back(strs[i]); hash.emplace(str, value_str); } } for(const auto& i : hash) { res.push_back(i.second); } return res; } };
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 (curRoot === null || root.length < curRoot.length) { curRoot = root; } } } return curRoot !== null ? curRoot : word; }) .join(' '); };
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 Solution { public: int hammingDistance(int x, int y) { int temp1, temp2, count = 0; for (int i=0; i<32; i++) { temp1 = x & (1<<i); temp2 = y & (1 << i); //cout << "temp1-" << temp1 << "temp2 " << temp2 <<endl; if (temp1 != temp2)count++; } return count; } };
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) { answer++; int a = queue.poll(); int b = queue.poll(); int temp = a + (2 * b); queue.add(temp); } if (queue.peek() < K ) { return -1; } return answer; } }
더 맵게.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)] max_path = 1 for i in range(m): for j in range(n): max_path = max(max_path, self.dfs(i, j, matrix, memo)) return max_path def dfs(self, i, j, matrix, memo): if memo[i][j] > 0: # already searched return memo[i][j] m, n = len(matrix), len(matrix[0]) curr_path = 1 for x, y in [(i - 1, j), (i, j - 1), (i + 1, j), (i, j + 1)]: if 0 <= x < m and 0 <= y < n and matrix[i][j] < matrix[x][y]: next_path = self.dfs(x, y, matrix, memo) curr_path = max(curr_path, 1 + next_path) memo[i][j] = curr_path return curr_path
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]; int right = vec[len - i - 1]; left = left ^ 1; right = right ^ 1; vec[i] = right; vec[len - i - 1] = left; } if (i * 2 < len) { vec[i] = vec[i] ^ 1; } } return A; } }; int main(int argc, char *argv[]) { string line; while (getline(cin, line)) { vector<vector<int>> input; walkString(input, line); vector<vector<int>> output = Solution().flipAndInvertImage(input); cout << toString(output) << endl; } return 0; }
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); } int compute_value(int n) { if(n==1) return 2; ll val=2; for(ll i=1;i<n;i+=1) { //cout<<val<<" "<<i<<endl; val=(val%mod*((2*i)%mod+1)%mod*2)%mod; ll x=modinverse(i+1); val=(val*x)%mod; } return (int)val; } };
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 answer is guaranteed to be unique (except for the order that it is in). from collections import deque class Solution: def k_closest(self, points, k): res = deque([]) for elem in points: # 각요소를 제곱하여 거리값을 구하고 배열로 거리값, 원래좌표를 넣어줬다. # 파이썬이기 때문에 루트를 굳이 씌워주지 않았다. res.append([[elem[0] ** 2 + elem[1] ** 2], elem]) sorting = deque(sorted(res)) answer = [] for _ in range(k): answer.append(sorting.popleft()[1]) return answer # heapq를 이용하여 푼 방법이다. # import heapq # # def cal_dist(point): # return math.sqrt(point[0] * point[0] + point[1] * point[1]) # def k_closest_builtin(points, k): # dists = [] # heap = [] # for point in points: # dist = cal_dist(point) # heapq.heappush(heap, dist) # dists.append(dist) # # kth_dist = [heapq.heappop(heap) for _ in range(k)][-1] # return [points[idx] for idx, dist in enumerate(dists) if dist <= kth_dist]
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(2); // // int[] array = reversePrint(head); // // } public static void main(String[] args) { String str1 = "3"; String str2 = "3"; int result = str1.compareTo(str2); System.out.println(result); } public static int[] reversePrint(ListNode head) { List<Integer> listNodes = new ArrayList<>(); ListNode temp = reversalListNode(listNodes, head); if (temp != null) { listNodes.add(temp.val); } int[] array = new int[listNodes.size()]; int i = 0; for (Integer val : listNodes) { array[i++] = val; } return array; } private static ListNode reversalListNode(List<Integer> listNodes, ListNode node) { if (node == null) { return null; } ListNode temp = reversalListNode(listNodes, node.next); if (temp != null) { listNodes.add(temp.val); } return node; } }
从尾到头打印链表.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; Map<String, List<String>> anagramGrouping = new HashMap<>(); for (String word : strs) { int[] anagramKeyCounter = new int[26]; for (Character c : word.toCharArray()) { anagramKeyCounter[((int) c - OFFSET)] += 1; } StringBuilder key = new StringBuilder(); for (int keyCounter : anagramKeyCounter) { key.append('#').append(keyCounter); } anagramGrouping.computeIfAbsent(key.toString(), k -> new ArrayList<>()).add(word); } return new ArrayList<>(anagramGrouping.values()); } public static void main(String[] args) { groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"}); groupAnagrams(new String[]{""}); groupAnagrams(new String[]{"a"}); } }
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<Integer>(); int n = sc.nextInt(); for(int i=0;i<n;i++) { A.add(sc.nextInt()); } int count=0; int val1=0,val2=0; for(int i=0;i<n;i++) { val1 = A.get(i); for(int j=i;j<n;j++) { val2 = val2+A.get(j); if(val2<0) count++; } val2=0; } System.out.println(count); } }
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 val; ListNode next; ListNode(int x) { val = x; } } public ListNode swapPairs(ListNode head) { ListNode prev = new ListNode(-1); //dont forget to point the first node to the head node prev.next = head; ListNode rhead = prev; while (prev.next != null && prev.next.next != null) { ListNode first = prev.next; ListNode second = first.next; ListNode tail = second.next; //make the second node point to the first node second.next = first; //make the first node point to the last node first.next = tail; //make the previous node point to the second node prev.next = second; //move previous node to the first node prev = first; } return rhead.next; } }
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]+1 == arr[i+1]: count += 1 if max_sequence < count: max_sequence = count else: count = 1 i+=1 return max_sequence def longest_conse_fast(arr): #O(n) solution using a set with constant lookup time if len(arr) ==0: return 0 if len(arr) ==1: return 1 arr= set(arr) li =[] max_sequence= 0 count = 1 i=0 for i in arr: if i-1 not in arr: num= i count = 1 while num+1 in arr: num+=1 count+=1 max_sequence= max(max_sequence, count) #same as if count > max_sequence: max_sequence= count #if count > max_sequence: #max_sequence= count return max_sequence if __name__ == '__main__': array = [100,101,102,103,104, 4, 200, 1, 3, 2] #array= [1] print(longest_conse_slow(array)) print(longest_conse_fast(array))
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(int i=0;i<nums.length;i++) { arr.add(nums[i]); rese.add(nums[i]); } } public int[] reset() { int [] ans=new int[rese.size()]; for(int i=0;i<rese.size();i++) { ans[i]=rese.get(i); } return ans; } public int[] shuffle() { Collections.shuffle(arr); int [] ans=new int[arr.size()]; for(int i=0;i<arr.size();i++) { ans[i]=arr.get(i); } return ans; } } }
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.pop(); k--; } if(s.empty() and val==0) continue; s.push(val); } while(k && !s.empty()) { --k; s.pop(); } while(!s.empty()){ string temp = to_string(s.top()); ans = temp + ans; s.pop(); } return ans = ans==""? "0" : ans; } };
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.clear(); } s.insert(sum); } return cnt; } };
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.push([...parts]); return; } for (let i = start; i < s.length; i++) { const word = s.substring(start, i + 1); if (!isPalindrome(word)) continue; parts.push(word); backtracking(i + 1, parts); parts.pop(); } } function isPalindrome(word, left = 0, right = word.length - 1) { while (left < right) { if (word[left] !== word[right]) return false; left++; right--; } return true; } }; var s = 'aab'; var expected = [ ['a', 'a', 'b'], ['aa', 'b'], ]; var result = partition(s); console.log(result, result.join() === expected.join()); var s = 'a'; var expected = [['a']]; var result = partition(s); console.log(result, result.join() === expected.join());
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; people.sort_unstable_by_key(|v| (-v[0], v[1])); let mut res = Vec::with_capacity(people.len()); for person in people { res.insert(person[1] as usize, person); } res }
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 index """ # D & C solution (as in lecture 6) # Time: O(nlogn) # Space: O(n), due to stack class Solution: def maxSubArray(self, nums: List[int]) -> int: def helper(l, h): if l > h: return float("-inf") m = l + (h - l)//2 left_max = helper(l, m-1) right_max = helper(m+1, h) running_sum, lresult, rresult = 0, 0, 0 for i in range(m-1, l-1, -1): running_sum += nums[i] lresult = max(lresult, running_sum) running_sum = 0 for i in range(m+1, h+1, 1): running_sum += nums[i] rresult = max(rresult, running_sum) return max(lresult + rresult + nums[m], left_max, right_max) return helper(0, len(nums)-1) """ The Divide-and-Conquer algorithm breaks nums into two halves and find the maximum subarray sum in them recursively. Well, the most tricky part is to handle the case that the maximum subarray spans the two halves. For this case, we use a linear algorithm: starting from the middle element and move to both ends (left and right ends), record the maximum sum we have seen. In this case, the maximum sum is finally equal to the middle element plus the maximum sum of moving leftwards and the maximum sum of moving rightwards. T(n) = 2*T(n/2) + O(n) """
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 "shifting" which forms the sequence: "abc" -> "bcd" -> ... -> "xyz" Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], A solution is: [ ["abc","bcd","xyz"], ["az","ba"], ["acef"], ["a","z"] ] */ public class Solution249 { public List<List<String>> groupStrings(String[] strings) { Map<String, List<String>> map = new HashMap<>(); for (String string : strings) { char[] array = string.toCharArray(); int min = array[0] - 'a'; for (int i = 0; i < array.length; i++) { if (array[i] - min >= 'a') { array[i] -= min; } else { array[i] += (26 - min); } } String key = new String(array); if (!map.containsKey(key)) { map.put(key, new ArrayList<>()); } map.get(key).add(string); } return new ArrayList<>(map.values()); } }
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) #define FOR(i,a,b) for(int i=(a);i<=(b);++i) #define RFOR(i,a,b) for(int i=(a);i>=(b);--i) #define FOREACH(it,c) for(typeof((c).begin())it=(c).begin();it!=(c).end();++it) #define CLR(x) memset((x),0,sizeof((x))) #define MP make_pair #define MPI make_pair<int, int> #define PB push_back typedef long long LL; typedef vector<int> VI; typedef vector<string> VS; typedef pair<int, int> PI; class Solution { public: vector<VI> res; VI mm; void doit(int idx, int n, int k) { if (idx == k) { res.PB(mm); } else { int st; if (idx == 0) st = 1; else st = mm[idx - 1] + 1; FOR(i,st,n) { mm[idx] = i; doit(idx + 1, n, k); } } } vector<vector<int> > combine(int n, int k) { res.clear(); mm.resize(k); doit(0, n, k); return res; } }; int main() { Solution s = Solution(); vector<VI> mm = s.combine(4, 2); REP(i,mm.size()) { REP(j,mm[i].size()) cout << mm[i][j] << " "; cout << endl; } return 0; }
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 reset any member data you declared, as // the same Threesum.ZigzagIterator instance will be reused for each test case. if (head == null) return; int n = 0; ListNode p = head; while (p.next != null) { p = p.next; n++; } if (n <= 1) return; int mid = n / 2; ListNode s = head; ListNode t = head.next; int i = 0; while (i < mid) { s = s.next; t = t.next; i++; } s.next = null; while (i < n) { ListNode tmp = t.next; t.next = s; s = t; t = tmp; i++; } p = head; while (p != s && p != null && s!= null) { ListNode pn = p.next; ListNode sn = s.next; p.next = s; s.next = pn; p = pn; s = sn; } } }
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 * * * 思路: * 中心插值 * 1. 先轮询当前值的相邻左右是否存在,若存在,则记录左右的可扩展长度 * 2. 新长度为 1 + 左扩展 + 右扩展 * 3. 更新最大连续长度 * 4. 更新当前值的连续长度,以及左右端点的连续长度 */ class Solution { public: int longestConsecutive(vector<int>& nums) { map<int, int> M; int ans = 0; for (int num : nums) { if (!M.count(num)) { int lower = M.count(num - 1) ? M[num - 1] : 0; // 左区间可扩展长度 int upper = M.count(num + 1) ? M[num + 1] : 0; // 右区间可扩展长度 int len = 1 + lower + upper; //cout << num << " " << len << endl; ans = max(ans, len); // 更新目标值 M[num] = len; // if (M.count(num - lower)) M[num - lower] = len; // 更新左端点的连续长度 if (M.count(num + upper)) M[num + upper] = len; // 更新右端点的连续长度 } } return ans; } };
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++) { // numRows번 세로로 내려가고 (numRows - 2)번 대각선 위로 올라가는 것을 반복한다. // 1. zigzag가 세로로 내려가는 경우 if (i % (numRows * 2 - 2) < numRows) { arr[i % (numRows * 2 - 2)].push(s[i]) // 2. zigzag가 대각선 위로 올라가는 경우 } else { arr[numRows - 1 - ((i % (numRows * 2 - 2)) - numRows + 1)].push(s[i]) } } // 베열에 분리되어 있는 알파벳들을 join하고 그것들을 한번더 join하여 return for (let i = 0; i < numRows; i++) arr[i] = arr[i].join('') return arr.join('') }
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::new(); let mut nums: Vec<i32> = Vec::new(); let mut marker = -1; for word in words { if word == "prev" { if marker > -1 { let s = nums[marker as usize]; marker -= 1; output.push(s); } else { output.push(-1); marker = -1; } } else { nums.push(word.parse::<i32>().unwrap()); marker = (nums.len() as i32) - 1; } } return output; } }
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 # get shortest length among all strings shortest_len = inf for string in strs: if len(string) < shortest_len: shortest_len = len(string) # check each char for each string add = True for char_index in range(0, shortest_len): for string_index in range(0, len(strs)-1): if strs[string_index][char_index] != strs[string_index+1][char_index]: add = False break if add: answer = answer + strs[0][char_index] 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 { return result[size / 2]; } } vector<int> mergeSortedArrays(vector<int>& nums1, vector<int>& nums2) { vector<int> result; int i = 0, j = 0; while (i < nums1.size() && j < nums2.size()) { if (nums1[i] < nums2[j]) { result.push_back(nums1[i]); i++; } else { result.push_back(nums2[j]); j++; } } while (i < nums1.size()) { result.push_back(nums1[i]); i++; } while (j < nums2.size()) { result.push_back(nums2[j]); j++; } return result; } };
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.start < r.start); } vector<Interval> merge(vector<Interval> &intervals) { vector<Interval> result; if (intervals.size() == 0) { return result; } sort(intervals.begin(), intervals.end(), mycomp); int ind = 0; result.push_back(intervals[ind]); for (int i = 1; i < intervals.size(); i++) { if (intervals[i].start <= result[ind].end) { result[ind].end = max(result[ind].end, intervals[i].end); } else { result.push_back(intervals[i]); ind++; } } return result; } }; int main() { Solution s; vector<Interval> intervals; intervals.push_back(Interval(1, 3)); intervals.push_back(Interval(2, 6)); intervals.push_back(Interval(8, 10)); intervals.push_back(Interval(0, 18)); vector<Interval> result = s.merge(intervals); cout << "Result: " << endl; for (int i = 0; i < result.size(); i++) { cout << "[" << result[i].start << ", " << result[i].end << "]" << endl; } return 0; }
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) { case 'R': arr[0]++; break; case 'L': arr[1]++; break; case 'U': arr[2]++; break; case 'D': arr[3]++; break; } } return arr[0] == arr[1] && arr[2] == arr[3]; } }; // @lc code=end
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;i++){ m[i][0]=""; if(i!=0){ m[i][4]=m[i][1]+m[i][5]; m[i][9]=m[i][1]+m[i-1][1]; } } } string intToRoman(int num) { int result[4]; int tens[4]={1000,100,10,1}; string ans=""; for(int i=0;i<4;i++){ result[i]=num/tens[i]; num=num-tens[i]*result[i]; }; for(int i=0;i<4;i++){ //cout<<result[i]<<" "; if(result[i]==0 or result[i]==4 or result[i]==9){ ans=ans+m[i][result[i]]; }else{ if(result[i]>=5){ ans=ans+m[i][5]; }; for(int j=0;j<result[i]%5;j++){ ans=ans+m[i][1]; } } }; return ans; }; }; int main(){ Solution sol; //cout<<sol.m[3][5]<<endl; cout<<sol.intToRoman(1994)<<endl; return 0; }
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 = head; ListNode *slow = head; while (fast != NULL && fast->next != NULL) { /**<手动画下元素只有3,4的情况*/ fast = fast->next->next; slow = slow->next; if(fast == slow) /**<快慢指针走了之后才判断哈 */ return true; } return false; } int main(int argc, char *argv[]) { /**<创建链表 */ vector<int> s = {1,2}; ListNode *list = creatList(s); bool output = hasCycle(list); /**<do some job */ std::cout << output << std::endl; return 0; }
_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<>(); for(int i = 0; i < arr.length; i++){ str.add(String.valueOf(arr[i])); } Collections.sort(str, Collections.reverseOrder()); System.out.println(answer); } public String solution(int[] numbers) { String answer = ""; return answer; } }
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: for i in dic[key]: if i in dic2: dic2[i] += 1 else: dic2[i] = 1 del dic[key] # 3. 추천 제품 찾기 se = set(dic.keys()) for i,_ in sorted(dic2.items(), key=lambda x: (-x[1], x[0])): new_se = set(se) for key in new_se: if i not in dic[key]: se.remove(key) new_se.add(key) if len(se) == 1: break if not se: se = new_se return se.pop()
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++){ if(i <= n){ inc[i] = 1; tillNow.push_back(i); solve(i+1,k-1,n-i,inc,tillNow,ans); tillNow.pop_back(); inc[i] = 0; } } } vector<vector<int>> combinationSum3(int k, int n) { vector<bool> inc(10,0); vector<int> tillNow; vector<vector<int>> ans; solve(1,k,n,inc,tillNow,ans); return ans; } };
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> #include<queue> #include<stack> #include<map> #include<set> #include<unordered_map> #include<unordered_set> #include<algorithm> using namespace std; int minOperations(vector<int>& nums, int x) { unordered_map<int, int> pre, suf; pre[0] = 0, suf[0] = 0; vector<int> temp = nums; int ans = INT32_MAX; temp.insert(temp.begin(), 0); for (int i = 1; i <= nums.size(); i++) { temp[i] += temp[i - 1]; pre[temp[i]] = i; } temp = nums; temp.insert(temp.end(), 0); for (int i = nums.size() - 1, j = 1; i >= 0; i--, j++) { temp[i] += temp[i + 1]; suf[temp[i]] = j; } for (auto &y : pre) { if (suf.count(x - y.first)) ans = min(ans, y.second + suf[x - y.first]); } if (ans > nums.size()) return -1; return ans == INT32_MAX ? -1 : ans; } int main() { int x, n; vector<int> nums; cin >> x; while (cin >> n) nums.push_back(n); cout << minOperations(nums, x) << endl; return 0; }
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************************ vector<int> v = {}; cout << v.size(); //0 vector<vector<int>> ans; ans.push_back(v); //{{}} //ans (which is vector of vectors of int) has one empty vector at its index 0 as its element ,so ans.size() is 1 and not 0. cout << ans.size(); //1 v = ans.at(0); //v={}; //but that means v is empty and its size is 0 v.push_back(1); //v={1}; //first element pushed back i.e. an integer 1 in the empty vector v. ans.push_back(v); //{{},{1}} for (vector<int> e : ans) { cout << e << " "; } vector<int> v = {};: This creates an empty vector of integers named "v." cout << v.size();: This line prints the size of the vector "v." Since "v" is empty, its size is 0. So, the output will be "0." vector<vector<int>> ans;: This declares a vector of vectors of integers named "ans." At this point, "ans" is empty. ans.push_back(v);: This pushes the vector "v" (which is empty) into the "ans" vector. So, "ans" now contains one element, which is an empty vector of integers. cout << ans.size();: This line prints the size of the "ans" vector. Since "ans" contains one element (an empty vector), the output will be "1." v = ans.at(0);: This line assigns the first element of the "ans" vector (which is the previously added empty vector) to the vector "v." Now, "v" also becomes an empty vector. v.push_back(1);: This line adds an integer element with the value 1 to the vector "v." Now, "v" contains one element, which is the integer 1. ans.push_back(v);: This line pushes the modified "v" vector (which contains the integer 1) into the "ans" vector. Now, "ans" contains two elements: the first one is an empty vector, and the second one is a vector containing the integer 1. for (vector<int> e : ans) { cout << e << " "; }: This loop iterates through the "ans" vector and prints each element. */ //ITERATIVE APPROACH //https://youtu.be/kYY9DotIKlo?list=PLzffTJx5aHaSJ4XaG55cI3Z0VrNOyLWpH //TIME COMPLEXITY:O(N*2^N) //N=SIZE OF ARRAY,n=size of ans i.e. saare subsets(2^N) //SPACE COMPLEXITY:O(N*2^N) //size of ans i.e. saare subsets(2^N) into N(ek element ki maximum sixe ho sakti hai); basically m*n vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> ans; //vector<int> v={}; //or vector<int>v; ans.push_back(v); for(int e:nums) //e=//1 //2 //3 { int n=ans.size(); //n=//1 //2 //4 for(int i=0;i<n;i++) //i=//0 //0,1 //0,1,2,3 { v=ans.at(i); //{} //{};{1} //{};{1};{2};{1,2} v.push_back(e); //{1} //{2};{1,2} //{3};{1,3};{2,3};{1,2,3} ans.push_back(v); //{{},{1}} //{{},{1},{2}};{{},{1},{2},{1,2}} //{{},{1},{2},{1,2},{3}} ; {{},{1},{2},{1,2},{3},{1,3}};{{},{1},{2},{1,2},{3},{1,3},{2,3}} ; {{},{1},{2},{1,2},{3},{1,3},{2,3},{1,2,3}} } } return ans; } }; //RECURSIVE APPROACH(BACKTRACK) #include<iostream> #include<vector> using namespace std; class Solution { public: void func(int index,vector<int>& nums,vector<int>& ds,vector<vector<int>> & ans) { if(index>=nums.size()) { ans.push_back(ds); return; } //take ds.push_back(nums[index]); func(index+1,nums,ds,ans); ds.pop_back(); //not take func(index+1,nums,ds,ans); } vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> ans; vector<int> ds; func(0,nums,ds,ans); return ans; } }; int main() { vector <int> vect {1,2,3}; vector<vector<int>> ans; Solution obj; ans=obj.subsets(vect); for(int i=0;i<ans.size();i++) { for(int j=0;j<ans[i].size();j++) { cout<<ans[i][j]<<" "; } cout<<endl; } return 0; }
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; sell = max(sell, buy + price); buy = max(buy, presell - price - fee); } return 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(); } public void start() { //example 1 if (true) { _700_SearchInBinarySearchTree c = new _700_SearchInBinarySearchTree(); TreeNode root = new TreeNode(4); root.left = new TreeNode(2, new TreeNode(1), new TreeNode(3)); root.right = new TreeNode(7); int val = 2; System.out.println("Found Tree = " + c.searchBST(root, val)); } } public TreeNode searchBST(TreeNode root, int val) { if (root == null) { return root; } Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); TreeNode result = null; while (!queue.isEmpty()) { root = queue.poll(); if (root.val == val) { result = root; break; } if (root.left != null) { queue.add(root.left); } if (root.right != null) { queue.add(root.right); } } return result; } }
_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(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ a[A[i]]--; a[A[j]]--; int find=X-A[i]-A[j]; if(find>=0&&a[find]>=1) return true; a[A[i]]++; a[A[j]]++; } } return false; //Your Code Here } };
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 string will not exceed 1,010. */ public class _0409_LongestPalindrome { public int longestPalindrome(String s) { int res = 0; if (s.length() == 0) return res; int[] count = new int[58]; for (char c : s.toCharArray()) count[c - 'A']++; int flag = 0; for (int num : count) { res += num / 2 * 2; if (num % 2 != 0) flag = 1; } return res + flag; } public static void main(String[] args) { String s = "abccccdd"; System.out.println(new _0409_LongestPalindrome().longestPalindrome(s)); } }
_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().reverseList(node); } /** * 迭代方法 * * @param head * @return */ public ListNode reverseList1(ListNode head) { if (head == null) { return null; } List<ListNode> listNodes = new ArrayList<>(); listNodes.add(head); for (ListNode next = head.next; next != null; next = next.next) { listNodes.add(next); } ListNode tmp = null; for (int i = listNodes.size() - 1; i >= 0; i--) { if (tmp == null) { tmp = listNodes.get(i); } else { tmp.next = listNodes.get(i); tmp = listNodes.get(i); } } tmp.next = null; return listNodes.get(listNodes.size() - 1); } public ListNode reverseList2(ListNode head) { ListNode prev = null; ListNode curr = head; while (curr != null) { ListNode nextTemp = curr.next; curr.next = prev; prev = curr; curr = nextTemp; } return prev; } /** * 递归的方法 * * @param head * @return */ public ListNode reverseList(ListNode head) { if (head == null || head.next == null) return head; ListNode p = reverseList(head.next); head.next.next = head; head.next = null; return p; } }
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 = tail = 0 for i in s: if i == "?": head += 1 else: break; for i in range(len(s)-1, -1, -1): if s[i] == "?": tail += 1 else: break; return [head, tail] def compare(self, s:str, sub:str) -> bool: if len(sub) > len(s): return False for i in range(len(sub)): if sub[i] == "?" or sub[i] == s[i]: continue else: return False return True def nearestIdx(self, s:str, sub:str) -> int: ''' if ans equals -1 means no result found ''' if len(s) < len(sub): return -1 ans = -1 head, tail = self.countQuestion(sub) if head == len(sub): return 0 if tail == 0: new_s = s[head:] new_sub = sub[head:] else: new_s = s[head:-tail] new_sub = sub[head:-tail] for i in range(len(new_s)): if new_s[i] == new_sub[0]: if self.compare(new_s[i:], new_sub): ans = i break return ans def isMatch(self, s, p): ''' process star singly, process ? and normal characters in one method. ''' if self.allStar(p): return True if p == "" and s == "": return True if p == "" and s != "": return False if s == "" and p != "": return False if p.find("*") == -1: if len(s) != len(p): return False for i in range(len(p)): if p[i] == "?" or s[i] == p[i]: continue else: return False return True head = p[:p.find("*")] tail = p[p.rfind("*")+1:] if len(head) + len(tail) > len(s): return False for i in range(len(head)): if head[i] == "?" or head[i] == s[i]: continue else: return False for i in range(len(tail)): if tail[i] == "?" or tail[i] == s[i-len(tail)]: continue else: return False if len(tail) == 0: mid_s = s[len(head):] mid_p = p[len(head):] else: mid_s = s[len(head): -len(tail)] mid_p = p[len(head): -len(tail)] split_p = mid_p.split("*") last = mid_s for sub_p in split_p: cur_idx = self.nearestIdx(last, sub_p) if cur_idx == -1: return False else: last = last[cur_idx + len(sub_p):] return True def main(): s = Solution() full = "aa" sub = "aa" i = s.isMatch(full, sub) print("the ans is:") print(i) return if __name__ == "__main__": main()
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 memory is allowed. * * For example, * Given this linked list: 1->2->3->4->5 * * For k = 2, you should return: 2->1->4->3->5 * * For k = 3, you should return: 3->2->1->4->5 * */ #include <iostream> #include <vector> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode *node = head; ListNode *prevNode = NULL; if (k == 1) { return head; } while (node != NULL) { ListNode *v[k]; int count = 0; ListNode *tmp = node; while (tmp != NULL && count < k) { v[count++] = tmp; tmp = tmp->next; } if (count != k) { break; } v[0]->next = v[k-1]->next; for (int i = k-1; i > 0; i--) { v[i]->next = v[i-1]; } if (head == v[0]) { head = v[k-1]; } else { prevNode->next = v[k-1]; } prevNode = v[0]; node = v[0]->next; } return head; } }; int main() { int a[] = {2, 5, 3, 4, 6, 2, 2}; ListNode *head = NULL, *tail = NULL; for (unsigned int i = 0; i < sizeof(a)/sizeof(a[0]); i++) { ListNode *node = new ListNode(a[i]); if (head == NULL) { head = tail = node; } else { tail->next = node; tail = node; } } ListNode *h = head; while (h != NULL) { cout << h->val << " "; h = h->next; } cout << endl; Solution s; head = s.reverseKGroup(head, 3); h = head; while (h != NULL) { cout << h->val << " "; h = h->next; } cout << endl; return 0; }
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 = 0; // 遍历条件 这里一旦数组index没有 并且 K等于0就跳出来了 while (len >= 0 || k != 0) { // 不能这样简单相加 int sum = num[len] + k % 10 + carry; int x = len < 0 ? 0 : num[len]; // 因为x和y中间可能任一一方提前结束 int y = k == 0 ? 0 : k % 10; int sum = x + y + carry; res.add(sum % 10); // 只能取最后1位 carry = sum / 10; // 计算carry len--; k = k / 10; // 每次都要去掉最后1位 取商 这里的目的是为了逐一去掉个位 1886→188→18→1 } // 这里!!重要,没有的话就会造成 888 + 666 = 554(1554的1 会丢掉) if (carry != 0) res.add(carry); Collections.reverse(res); return res; } }
_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. * <p> * <p> * <p> * Example 1: * <p> * Input: "abab" * Output: True * Explanation: It's the substring "ab" twice. * Example 2: * <p> * Input: "aba" * Output: False * Example 3: * <p> * Input: "abcabcabcabc" * Output: True * Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.) * <p> * Created by zjm on 2019/8/10 09:14 */ public class RepeatedSubstringPattern { //直接根据题意采用暴力解法 public boolean repeatedSubstringPattern(String s) { int loop; for(int i = 1; i < s.length() / 2 + 1; i++) { if(s.charAt(i) == s.charAt(0)) { loop = i; while(i < s.length() && s.charAt(i) == s.charAt(i % loop)) { i++; } if(i == s.length() && i % loop == 0) { return true; }else { i = loop; } } } return false; } //将s根据每个因子划分子串,如果每个因子长度的子串重复可以组成s,则返回true public boolean repeatedSubstringPatternBetter(String s) { for(int i = s.length() / 2; i >= 1; i--) { if(s.length() % i == 0) { int index = s.length() / i; StringBuilder sb = new StringBuilder(); for(int j = 0; j < index; j++) { sb.append(s.substring(0, i)); } if(sb.toString().equals(s)) { return true; } } } return false; } public boolean repeatedSubstringPatternBetter2(String s) { for(int i = s.length() / 2; i >= 1; i--) { if(s.length() % i == 0) { if(s.split(s.substring(0, i)).length == 0) { return true; } } } return false; } }
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(numbers[middle]>numbers[right]) left=middle; else if(numbers[middle]<numbers[right])right=middle; else { right--; } } return min(numbers[left],numbers[right]); } };
面试题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) FROM Employee GROUP BY DepartmentId ) ;
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); } } void push(int val) { if(minimum.empty() || val <= getMin()){ minimum.push_back(val); } myStack.push_back(val); } void pop() { if(myStack.back() == getMin()) minimum.pop_back(); myStack.pop_back(); } int top() { return myStack.back(); } int getMin() { return minimum.back(); } private: std::vector<int> myStack; std::vector<int> minimum; }; int main(){ MinStack* obj = new MinStack({2,3,4,5,9,-10,-2}); obj->push(5); obj->pop(); int param_3 = obj->top(); int param_4 = obj->getMin(); std::cout << param_3 <<std::endl; std::cout << param_4 <<std::endl; }
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 { for i := 1; i < len(this.Arr); i++ { if this.Arr[i] == 1 { this.Arr[i] = 0 return i } } return -1 } func (this *SmallestInfiniteSet) AddBack(num int) { this.Arr[num] = 1 } /** * Your SmallestInfiniteSet object will be instantiated and called as such: * obj := Constructor(); * param_1 := obj.PopSmallest(); * obj.AddBack(num); */
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; } function alternate(T) { const result = []; const stack = []; for (let i = T.length - 1; i >= 0; i--) { while (stack.length > 0 && T[i] >= T[stack[stack.length - 1]]) { stack.pop(); } if (stack.length > 0) { result[i] = stack[stack.length - 1] - i; } else { result[i] = 0; } stack.push(i); } return result; } let input = [73, 74, 75, 71, 69, 72, 76, 73] let output = alternate(input); console.log(output);
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.ready()) { int aByte = fileReader.read(); symbols[aByte] += 1; } } for (int i = 0; i < symbols.length; i++) { if (symbols[i] != 0) { System.out.println((char) i + " " + symbols[i]); } } } }
Solution.java
java
623
en
java
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
22