前言
这个星期学习完了力扣上面的数组和字符串一书并且完成了其中的几个典型例题,接下来描述我的学习心得与体会
一、学习重点
典型例题,代码与程序截图(ps:所有程序均使用C#进行编写)
1.寻找数组的中心索引
题目:给你一个整数数组 nums,请编写一个能够返回数组 “中心下标” 的方法。
数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。 如果数组不存在中心下标,返回 -1 。如果数组有多个中心下标,应该返回最靠近左边的那一个。using System;
namespace LeeCodeText1
{
class Program
{
static void Main(string[] args)
{
int[] nums = { 1, 7, 3, 6, 5, 6 };
Solution s = new Solution();
int result = s.pivotIndex(nums);
Console.WriteLine(result);
}
}
class Solution
{
public int pivotIndex(int[] nums)
{
int sum = 0, flag = 0, end = 0;
for (int i = 0; i < nums.Length; i++)
{
sum += nums[i];
}
if (sum - nums[0] == 0)
{
return 0;
}
for (int j = 0; j < nums.Length; j++)
{
flag += nums[j];
if (j != 0)
{
end = flag - nums[j];
}
while (end == sum - flag)
{
return j;
}
}
return -1;
}
}
}
2.反转字符串
题目:编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。 你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。using System;
namespace LeeCodeText1
{
class Program
{
static void Main(string[] args)
{
char[] c = { 'h','e','l','l','o','w' };
Solution s = new Solution();
s.ReverseString(c);
Console.WriteLine(c);
}
}
public class Solution
{
public void ReverseString(char[] s)
{
int start = 0;
int end = s.Length - 1;
char temp;
while (start <= end)
{
temp = s[start];
s[start] = s[end];
s[end] = temp;
start++;
end--;
}
}
}
}
3.移动零
题目:给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
using System;
namespace LeeCodeText1
{
class Program
{
static void Main(string[] args)
{
int[] c = {0,1,0,3,12};
Solution s = new Solution();
s.MoveZeroes(c);
for(int i = 0;i < c.Length; i++)
{
Console.Write(c[i]);
}
}
}
public class Solution
{
public void MoveZeroes(int[] nums)
{
int slow = 0;
int temp = 0;
for (int fast = 0; fast < nums.Length; fast++)
{
if (nums[fast] != 0)
{
temp = nums[slow];
nums[slow] = nums[fast];
nums[fast] = temp;
slow++;
}
}
}
}
}
二、学习心得
第一次写博客同时也是第一次了解学习C#,使用起来比较生疏,但俗话说的好Practice makes perfect,多加练习也能熟练掌握。这一个星期我不仅学习了C#的基础语法,字符串的增删改查还完成了力扣中数组和字符串一书的学习以及经典例题的训练。虽然对于我一个小白来说上手比较困难,每题都要思索良久,但是逐渐掌握了他的语法和基本使用,还是收获颇丰。希望我这股劲能一直保持下去,加油。
三、gitee代码链接
*须知少年凌云志,曾许人间第一流。*