简单的数据结构与算法(一)

1.001:环形链表

public bool HasCycle(ListNode head)

{

if (head == null) return false;

 

HashSet<ListNode> bill = new HashSet<ListNode>();

 

while (head != null)

{

if (bill.Contains(head))

{

return true;

}

else

{

bill.Add(head);

}

head = head.next;

}

return false;

}

1.002:删除排序数组中的重复项

public int RemoveDuplicates(int[] nums)

{

if (nums.Length == 0) return 0;

int i = 0;

for (int j = 1; j < nums.Length; j++)

{

if (nums[j] != nums[i])

{

i++;

nums[i] = nums[j];

}

}

 

return i + 1;

}

1.003:合并两个有序链表

public ListNode MergeTwoLists(ListNode l1, ListNode l2)

{

ListNode head = new ListNode(0);

ListNode cur = head;

while (l1 != null && l2 != null)

{

if (l1.val < l2.val)

{

cur.next = l1;

cur = l1;

l1 = l1.next;

}

else

{

cur.next = l2;

cur = l2;

l2 = l2.next;

}

}

 

if (l1 == null)

{

cur.next = l2;

}

if (l2 == null)

{

cur.next = l1;

}

 

return head.next;

}

1.004:最大子序和

public int MaxSubArray(int[] nums)

{

if (nums.Length == 0) return 0;

int result = nums[0];

int current = nums[0];

for (int i = 1; i < nums.Length; i++)

{

if (current < 0) current = nums[i];

else current += nums[i];

if (current >= result)

{

result = current;

}

}

return result;

}

1.005:有效的括号

public bool IsValid(string s)

{

if (string.IsNullOrEmpty(s)) return true;

Dictionary<char, char> dict = new Dictionary<char, char>();

dict.Add(')', '(');

dict.Add(']', '[');

dict.Add('}', '{');

Stack<char> stack = new Stack<char>();

for (int i = 0; i < s.Length; i++)

{

if (stack.Count == 0)

{

stack.Push(s[i]);

continue;

}

char temp;

dict.TryGetValue(s[i], out temp);

if (stack.Peek() == temp) stack.Pop();

else

stack.Push(s[i]);

}

 

if (stack.Count == 0) return true;

else

return false;

}

1.006:相交链表

public class Solution {

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {

/**

定义两个指针, 第一轮让两个到达末尾的节点指向另一个链表的头部, 最后如果相遇则为交点(在第一轮移动中恰好抹除了长度差)

两个指针等于移动了相同的距离, 有交点就返回, 无交点就是各走了两条指针的长度

**/

if(headA == null || headB == null) return null;

ListNode pA = headA, pB = headB;

// 在这里第一轮体现在pA和pB第一次到达尾部会移向另一链表的表头, 而第二轮体现在如果pA或pB相交就返回交点, 不相交最后就是null==null

while(pA != pB) {

pA = pA == null ? headB : pA.next;

pB = pB == null ? headA : pB.next;

}

return pA;

}

}

1.007:独特的电子邮件地址

public int NumUniqueEmails(string[] emails)

{

List<string> list = new List<string>();

for (int i = 0; i < emails.Length; i++)

{

string k = emails[i];

string[] j = k.Split('@');

string prev = j[0];

int index = prev.IndexOf('+');

prev = prev.Substring(0, index);

string[] bill = prev.Split('.');

string jj = string.Join("", bill);

string w = jj + "@" + j[1];

if (!list.Contains(w))

{

list.Add(w);

}

}

return list.Count;

}

1.008:反转图像

public int[][] FlipAndInvertImage(int[][] A)

{

//GetUpperBound可以获取数组的最高下标。

//GetLowerBound可以获取数组的最低下标。

//int [][] 交错数组

//数组都是引用类型

for (int i = 0; i <= A.GetUpperBound(0); i++)

{

Stack<int> kk = new Stack<int>();

for (int j = 0; j <= A.GetUpperBound(0); j++)

{

kk.Push(A[i][j]);

}

for (int j = 0; j <= A.GetUpperBound(0); j++)

{

A[i][j] = kk.Pop();

}

for (int j = 0; j <= A.GetUpperBound(0); j++)

{

if (A[i][j] == 1)

{

A[i][j] = 0;

}else if(A[i][j]==0)

{

A[i][j] = 1;

}

}

}

return A;

}

1.009:唯一摩尔斯密码词

public int UniqueMorseRepresentations(string[] words)

{

List<string> kkkk = new List<string>();

 

String[] a = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };

char[] b = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };

 

for (int i = 0; i < words.Length; i++)

{

char[] jiu = words[i].ToCharArray();

 

StringBuilder kk = new StringBuilder();

for (int j = 0; j < jiu.Length; j++)

{

for (int k = 0; k < b.Length; k++)

{

if (jiu[j] == b[k])

{

kk.Append(a[k]);

}

}

}

string wo = kk.ToString();

if (!kkkk.Contains(wo))

{

kkkk.Add(wo);

}

}

return kkkk.Count;

}

1.010:汉明距离

public int HammingDistance(int x, int y)

{

int biil = x ^ y;

//有多少个1距离就是多少

string kk = Convert.ToString(biil, 2);

int count = 0;

for(int i = 0; i < kk.Length; i++)

{

if (kk[i] == '1')

{

count++;

}

}

return count;

}

1.011:增减字符串匹配

public int[] DiStringMatch(string S)

{

int[] res = new int[S.Length+ 1];

int I = 0, D = S.Length, sz = D;

for (int i = 0; i < sz; i++)

{

char s = S[i];

if (s.Equals('I'))

res[i] = I++;

else if (s.Equals ('D'))

res[i] = D--;

}

res[sz] = D;

return res;

}

1.012:合并二叉树

public TreeNode MergeTrees(TreeNode t1, TreeNode t2)

{

if (t1 == null) return t2;

if (t2 == null) return t1;

 

t1.val += t2.val;

t1.left = MergeTrees(t1.left, t2.left);

t1.right = MergeTrees(t2.left, t1.left);

return t1;

}

1.013:键盘行

public string[] FindWords(string[] words)

{

string[] rows = new string[3] { "qwertyuiop", "asdfghjkl", "zxcvbnm" };

List<string> list = rows.ToList();

 

return words.ToList().Where(go =>

{

string strArray = go.ToLower();

return list.Any(row => strArray.ToList().All(item => row.Contains(item)));

}).ToArray();

}

1.014:最接近原点的k个点

public int[][] KClosest(int[][] points, int K)

{

//交错数组是数组的数组

var result = from array in points

orderby Math.Pow(array[0], 2) + Math.Pow(array[1], 2)

select array;

return result.Take(K).ToArray();

}

1.015:数组拆分I

public int ArrayPairSum(int[] nums)

{

int sum = 0;

Array.Sort(nums);

for (int i = 0; i < nums.Length; i += 2)

{

sum += nums[i];

}

return sum;

}

1.016:各位相加

public int AddDigits(int num) {

int sum = 0;

while (num > 9) //直至num为1位数

{

while (num!=0)

{

sum += num % 10;

num /= 10;

}

num = sum; //重新给num赋值

sum = 0;

}

return num;

}

1.017:字符的最短距离

public int[] ShortestToChar(string S, char C)

{

List<int> res = new List<int>();

List<int> list1 = new List<int>();

char[] array = S.ToCharArray();

for (int i = 0; i < S.Length; i++)

{

if (array[i] == C)

{

list1.Add(i);

}

}

 

for (int i = 0; i < S.Length; i++)

{

int index = list1.Min(n => Math.Abs(n - i));

res.Add(index);

}

return res.ToArray();

}

1.018:杨辉三角

private static IList<IList<int>> Generate(int numRows)

{

if (numRows == 0)

{

return new int[][] { };

}

int[][] res = new int[numRows][];

for (int i = 0; i < res.Length; i++)

{

res[i] = new int[i + 1];

}

 

res[0][0] = 1;

for (int i = 1; i < numRows; i++)

{

res[i][0] = 1;

 

for (int j = 1; j < i + 1; j++)

{

if (j >= i)

{

res[i][j] = res[i - 1][j - 1];

}

else

{

res[i][j] = res[i - 1][j - 1] + res[i - 1][j];

}

}

}

return res;

}

 

1.019:三角形最大周长

public int LargestPerimeter(int[] A)

{

Array.Sort(A);

 

for (int i = A.Length - 3; i >= 0; --i)

{

 

if (A[i] + A[i + 1] > A[i + 2])

{

return A[i] + A[i + 1] + A[i + 2];

}

}

return 0;

}

1.020:用栈实现队列

public class MyQueue

{

private Stack<int> _stack = null;

/** Initialize your data structure here. */

public MyQueue()

{

_stack = new Stack<int>();

}

 

/** Push element x to the back of queue. */

public void Push(int x)

{

var stack = new Stack<int>();

stack.Push(x);

//这里反转不会影响原来的,数组会影响的,而且栈的所谓索引跟数组这些是反的

var temp = _stack.Reverse().ToList();

foreach (var item in temp)

{

stack.Push(item);

}

 

_stack = stack;

}

 

/** Removes the element from in front of queue and returns that element. */

public int Pop()

{

return _stack.Pop();

}

 

/** Get the front element. */

public int Peek()

{

return _stack.Peek();

}

 

/** Returns whether the queue is empty. */

public bool Empty()

{

return _stack.Count == 0;

}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值