Цена за 48 часов в ленте | 1000,00 |
Цена за 1 час закрепления | — |
Взаимопиар | Нет |
Input: nums = [3,5,2,1,6,4]
Output: [3,5,1,6,2,4]
Explanation: [1,6,2,5,3,4] is also accepted.
public class Solution {
private void Swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
public void WiggleSort(int[] nums) {
for (int i = 0; i < nums.Length - 1; i++) {
if ((i % 2 == 0 && nums[i] > nums[i + 1]) || (i % 2 == 1 && nums[i] < nums[i + 1])) {
Swap(nums, i, i + 1);
}
}
}
}
Input: nums = [1,0,1,0,1], goal = 2
Output: 4
using System.Collections.Generic;
public class Solution {
public int NumSubarraysWithSum(int[] nums, int goal) {
var prefixSumCount = new Dictionary();
prefixSumCount[0] = 1;
int currentSum = 0;
int count = 0;
foreach (int num in nums) {
currentSum += num;
if (prefixSumCount.ContainsKey(currentSum - goal)) {
count += prefixSumCount[currentSum - goal];
}
if (prefixSumCount.ContainsKey(currentSum)) {
prefixSumCount[currentSum]++;
} else {
prefixSumCount[currentSum] = 1;
}
}
return count;
}
}
Input: s = "0"
Output: true
public class Solution {
public bool IsNumber(string s) {
bool seenDigit = false;
bool seenExponent = false;
bool seenDot = false;
for (int i = 0; i < s.Length; i++) {
char curr = s[i];
if (Char.IsDigit(curr)) {
seenDigit = true;
} else if (curr == '+' || curr == '-') {
if (i > 0 && s[i - 1] != 'e' && s[i - 1] != 'E') {
return false;
}
} else if (curr == 'e' || curr == 'E') {
if (seenExponent || !seenDigit) {
return false;
}
seenExponent = true;
seenDigit = false;
} else if (curr == '.') {
if (seenDot || seenExponent) {
return false;
}
seenDot = true;
} else {
return false;
}
}
return seenDigit;
}
}
Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,2,1,3]
Объяснение: Всего есть 4 курса, которые нужно пройти. Чтобы взять курс 3, вы должны завершить оба курса 1 и 2. Оба курса 1 и 2 должны быть взяты после того, как вы завершите курс 0.
Таким образом, один из правильных порядков курсов — [0,1,2,3]. Другой правильный порядок — [0,2,1,3].
public class Solution {
private const int WHITE = 1;
private const int GRAY = 2;
private const int BLACK = 3;
public int[] FindOrder(int numCourses, int[][] prerequisites) {
bool isPossible = true;
var color = new Dictionary();
var adjList = new Dictionary>();
var topologicalOrder = new List();
for (int i = 0; i < numCourses; i++) color[i] = WHITE;
foreach (var relation in prerequisites) {
int dest = relation[0];
int src = relation[1];
if (!adjList.ContainsKey(src)) adjList[src] = new List();
adjList[src].Add(dest);
}
for (int i = 0; i < numCourses && isPossible; i++) {
if (color[i] == WHITE) {
Dfs(i, color, adjList, ref isPossible, topologicalOrder);
}
}
if (isPossible) {
var order = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
order[i] = topologicalOrder[numCourses - i - 1];
}
return order;
} else {
return new int[0];
}
}
private void Dfs(int node, Dictionary color, Dictionary> adjList,
ref bool isPossible, List topologicalOrder) {
if (!isPossible) return;
color[node] = GRAY;
if (adjList.ContainsKey(node)) {
foreach (int neighbor in adjList[node]) {
if (color[neighbor] == WHITE) {
Dfs(neighbor, color, adjList, ref isPossible, topologicalOrder);
} else if (color[neighbor] == GRAY) {
isPossible = false;
}
}
}
color[node] = BLACK;
topologicalOrder.Add(node);
}
}
Input
["WordDistance", "shortest", "shortest"]
[[["practice", "makes", "perfect", "coding", "makes"]], ["coding", "practice"], ["makes", "coding"]]
Output
[null, 3, 1]
Explanation
WordDistance wordDistance = new WordDistance(["practice", "makes", "perfect", "coding", "makes"]);
wordDistance.shortest("coding", "practice"); // return 3
wordDistance.shortest("makes", "coding"); // return 1
using System;
using System.Collections.Generic;
public class WordDistance {
private Dictionary> locations;
public WordDistance(string[] words) {
locations = new Dictionary>();
for (int i = 0; i < words.Length; i++) {
if (!locations.ContainsKey(words[i])) {
locations[words[i]] = new List();
}
locations[words[i]].Add(i);
}
}
public int Shortest(string word1, string word2) {
List loc1 = locations[word1];
List loc2 = locations[word2];
int l1 = 0, l2 = 0, minDiff = int.MaxValue;
while (l1 < loc1.Count && l2 < loc2.Count) {
minDiff = Math.Min(minDiff, Math.Abs(loc1[l1] - loc2[l2]));
if (loc1[l1] < loc2[l2]) {
l1++;
} else {
l2++;
}
}
return minDiff;
}
}
Input: logs = [[0,2,0],[1,0,1],[3,0,3],[4,1,2],[7,3,1]], n = 4
Output: 3
Explanation: At timestamp = 3, all the persons (i.e., 0, 1, 2, and 3) become friends.
public class UnionFind {
private int[] parent;
private int[] rank;
public UnionFind(int n) {
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 1;
}
}
public int Find(int x) {
if (parent[x] != x) {
parent[x] = Find(parent[x]);
}
return parent[x];
}
public bool Union(int x, int y) {
int rootX = Find(x);
int rootY = Find(y);
if (rootX != rootY) {
if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
return true;
}
return false;
}
}
public class Solution {
public int EarliestAcq(int[][] logs, int n) {
Array.Sort(logs, (a, b) => a[0].CompareTo(b[0]));
var uf = new UnionFind(n);
int groupCount = n;
foreach (var log in logs) {
int timestamp = log[0];
int friendA = log[1];
int friendB = log[2];
if (uf.Union(friendA, friendB)) {
groupCount--;
}
if (groupCount == 1) {
return timestamp;
}
}
return -1;
}
}
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
public class Solution {
public bool ValidateStackSequences(int[] pushed, int[] popped) {
Stack stack = new Stack();
int j = 0;
foreach (int x in pushed) {
stack.Push(x);
while (stack.Count > 0 && j < popped.Length && stack.Peek() == popped[j]) {
stack.Pop();
j++;
}
}
return j == popped.Length;
}
}
Input: strs = ["cba","daf","ghi"]
Output: 1
public class Solution {
public int MinDeletionSize(string[] strs) {
int count = 0;
int rows = strs.Length;
int cols = strs[0].Length;
for (int col = 0; col < cols; col++) {
for (int row = 1; row < rows; row++) {
if (strs[row][col] < strs[row - 1][col]) {
count++;
break;
}
}
}
return count;
}
}
Input: board = [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 3
public class Solution {
public int NumRookCaptures(char[][] board) {
int CountPawns(int x, int y, int dx, int dy) {
while (x >= 0 && x < 8 && y >= 0 && y < 8) {
if (board[x][y] == 'B') break;
if (board[x][y] == 'p') return 1;
x += dx;
y += dy;
}
return 0;
}
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (board[i][j] == 'R') {
return CountPawns(i, j, -1, 0) + CountPawns(i, j, 1, 0) +
CountPawns(i, j, 0, -1) + CountPawns(i, j, 0, 1);
}
}
}
return 0;
}
}
Input: sentence1 = ["great","acting","skills"], sentence2 = ["fine","drama","talent"], similarPairs = [["great","fine"],["drama","acting"],["skills","talent"]]
Output: true
using System;
using System.Collections.Generic;
public class Solution {
public int[] AsteroidCollision(int[] asteroids) {
Stack stack = new Stack();
foreach (int asteroid in asteroids) {
bool alive = true;
while (alive && asteroid < 0 && stack.Count > 0 && stack.Peek() > 0) {
int last = stack.Pop();
if (last == -asteroid) {
alive = false;
} else if (last > -asteroid) {
stack.Push(last);
alive = false;
}
}
if (alive) {
stack.Push(asteroid);
}
}
int[] result = new int[stack.Count];
for (int i = result.Length - 1; i >= 0; i--) {
result[i] = stack.Pop();
}
return result;
}
}
Input: sentence1 = ["great","acting","skills"], sentence2 = ["fine","drama","talent"], similarPairs = [["great","fine"],["drama","acting"],["skills","talent"]]
Output: true
using System;
using System.Collections.Generic;
public class Solution {
public bool AreSentencesSimilar(string[] sentence1, string[] sentence2, IList> similarPairs) {
if (sentence1.Length != sentence2.Length) {
return false;
}
var similar = new Dictionary>();
foreach (var pair in similarPairs) {
var x = pair[0];
var y = pair[1];
if (!similar.ContainsKey(x)) {
similar[x] = new HashSet();
}
if (!similar.ContainsKey(y)) {
similar[y] = new HashSet();
}
similar[x].Add(y);
similar[y].Add(x);
}
for (int i = 0; i < sentence1.Length; i++) {
var w1 = sentence1[i];
var w2 = sentence2[i];
if (w1 != w2 && (!similar.ContainsKey(w1) || !similar[w1].Contains(w2))) {
return false;
}
}
return true;
}
}
Input: arr = [6,2,3,4]
Output: [6,3,3,4]
using System;
using System.Collections.Generic;
public class Solution {
public int[] TransformArray(int[] arr) {
bool changed;
do {
changed = false;
int[] newArr = (int[])arr.Clone();
for (int i = 1; i < arr.Length - 1; i++) {
if (arr[i] < arr[i - 1] && arr[i] < arr[i + 1]) {
newArr[i]++;
changed = true;
} else if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) {
newArr[i]--;
changed = true;
}
}
arr = newArr;
} while (changed);
return arr;
}
}
Input: nums = [1,2,1,3,2,5]
Output: [3,5]
Explanation: [5, 3] is also a valid answer.
public class Solution {
public int[] SingleNumber(int[] nums) {
int xor = 0;
foreach (int num in nums) {
xor ^= num;
}
int diff = xor & -xor;
int[] res = new int[2];
foreach (int num in nums) {
if ((num & diff) == 0) {
res[0] ^= num;
} else {
res[1] ^= num;
}
}
return res;
}
}
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: true
public class Solution {
private int Dist(int[] p1, int[] p2) {
return (p2[1] - p1[1]) * (p2[1] - p1[1]) + (p2[0] - p1[0]) * (p2[0] - p1[0]);
}
private bool Check(int[] p1, int[] p2, int[] p3, int[] p4) {
return Dist(p1, p2) > 0 &&
Dist(p1, p2) == Dist(p2, p3) &&
Dist(p2, p3) == Dist(p3, p4) &&
Dist(p3, p4) == Dist(p4, p1) &&
Dist(p1, p3) == Dist(p2, p4);
}
public bool ValidSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
return Check(p1, p2, p3, p4) ||
Check(p1, p3, p2, p4) ||
Check(p1, p2, p4, p3);
}
}
Input: currentState = "++++"
Output: true
Explanation: The starting player can guarantee a win by flipping the middle "++" to become "+--+".
public class Solution {
public bool CanWin(string currentState) {
char[] stateArray = currentState.ToCharArray();
for (int i = 0; i < stateArray.Length - 1; i++) {
if (stateArray[i] == '+' && stateArray[i + 1] == '+') {
stateArray[i] = '-';
stateArray[i + 1] = '-';
string newState = new string(stateArray);
if (!CanWin(newState)) {
stateArray[i] = '+';
stateArray[i + 1] = '+';
return true;
}
stateArray[i] = '+';
stateArray[i + 1] = '+';
}
}
return false;
}
}
Input: values = [1,2,3]
Output: 6
public class Solution {
public int MinScoreTriangulation(int[] values) {
int n = values.Length;
int[,] dp = new int[n, n];
for (int length = 2; length < n; ++length) {
for (int i = 0; i < n - length; ++i) {
int j = i + length;
dp[i, j] = int.MaxValue;
for (int k = i + 1; k < j; ++k) {
dp[i, j] = Math.Min(dp[i, j], dp[i, k] + dp[k, j] + values[i] * values[j] * values[k]);
}
}
}
return dp[0, n - 1];
}
}
Input: seats = [1,0,0,0,1,0,1]
Output: 2
Explanation:
If Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.
If Alex sits in any other open seat, the closest person has distance 1.
Thus, the maximum distance to the closest person is 2.
public class Solution {
public int MaxDistToClosest(int[] seats) {
int n = seats.Length;
int prev = -1, future = 0;
int ans = 0;
for (int i = 0; i < n; ++i) {
if (seats[i] == 1) {
prev = i;
} else {
while (future < n && (seats[future] == 0 || future < i)) {
future++;
}
int left = prev == -1 ? n : i - prev;
int right = future == n ? n : future - i;
ans = Math.Max(ans, Math.Min(left, right));
}
}
return ans;
}
}
Input
["MyCalendarTwo", "book", "book", "book", "book", "book", "book"]
[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]
Output
[null, true, true, true, false, true, true]
using System;
using System.Collections.Generic;
public class MyCalendarTwo {
private List<(int, int)> events;
private List<(int, int)> overlaps;
public MyCalendarTwo() {
events = new List<(int, int)>();
overlaps = new List<(int, int)>();
}
public bool Book(int start, int end) {
foreach (var (os, oe) in overlaps) {
if (start < oe && end > os) {
return false;
}
}
foreach (var (es, ee) in events) {
if (start < ee && end > es) {
overlaps.Add((Math.Max(start, es), Math.Min(end, ee)));
}
}
events.Add((start, end));
return true;
}
}