题单分类:DeepSeek刷力扣辅助题单 存留记录-CSDN博客
27
27. 移除元素 - 力扣(LeetCode)
这道题就一个点
1.数组在内存上连续 所以要么赋值覆盖,要么移动覆盖,但是它要求了前
k
个元素 所以只能移动覆盖
所以我有了如下思考过程:
3223 , 3举例
如果是判断相等:nums[i]=val 然后nums[i]=nums[i+1]向前覆盖,会产生越界
如果是判断不等,i会从2开始,然后nums[i]=nums[i+1]向前覆盖 还是会越界
所以问题出在了nums[i]=nums[i+1]这里,如果有一个新的变量指向前一个数 不出现i+1就好了,然后就出来了,所谓的双指针
public class Solution {
public int RemoveElement(int[] nums, int val) {
int k = 0;
for (int i = 0; i < nums.Length; i++) {
if (nums[i] != val) {
nums[k] = nums[i];
k++;
}
}
return k;
}
}
704
704. 二分查找 - 力扣(LeetCode)
不可能这么简单
static int Search(int[] nums, int target)
{
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] == target) {
return i;
}
}
return -1;
}
所以我想标题写了二分查找 那我就二分查🤯
没有要点,需要知道C# int强转浮点数向下取整
public class Solution {
public int Search(int[] nums, int target) {
//二分查找
int Left = 0;
int Right = nums.Length - 1;
while (Left <= Right) {
int mid = Left + (Right - Left) / 2;
//中间比
if (nums[mid] == target)
return mid;
if (nums[mid] > target)
{
Right = mid - 1;
}
else {
Left = mid + 1;
}
}
return -1;
}
}
344
344. 反转字符串 - 力扣(LeetCode)
笑死了
List<char> chars = new List<char>(s);
chars.Reverse();
for (int i = 0; i < chars.Count; i++)
{
s[i] = chars[i];
}
}
不要再狐闹了
int Left = 0;
int Right = s.Length - 1;
char temp ;
while (Left<Right)
{
temp = s[Left];
s[Left] = s[Right];
s[Right] = temp;
Left++;
Right--;
}
386
386. 字典序排数 - 力扣(LeetCode)
我想到了用字典尝试 然后找到value=1的值 花了十几分钟,可以 但是不是最好的
using System;
using System.Collections.Generic;
public class Solution {
public int FirstUniqChar(string s) {
Dictionary<char, int> charCount = new Dictionary<char, int>();
foreach (char c in s) {
if (charCount.ContainsKey(c)) {
charCount[c]++;
} else {
charCount.Add(c, 1);
}
}
for (int i = 0; i < s.Length; i++) {
if (charCount[s[i]] == 1) {
return i;
}
}
return -1;
}
}
可以简化这个字典为数组 因为char是ascll码转来的 所以可以将其作为数组的下标 想到的人真是天才
int[] Arr = new int[128];
foreach (var item in s)
{
Arr[item]++;
}
for (int i = 0; i < s.Length; i++)
{
if (Arr[s[i]] == 1)
return i;
}
return -1;