面试笔试杂项积累-leetcode 136-140

来源:互联网 发布:arduino摄像头编程 编辑:程序博客网 时间:2024/05/20 03:38

136.136-Single Number-Difficulty: Medium

Given an array of integers, every element appearstwice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

思路

数组中的所有数都是两个,只有一个是一个数,找到那个数

先sort,然后找

public class Solution {    public int SingleNumber(int[] nums) {                Array.Sort(nums);        for (int i = 1; i < nums.Length; i += 2)        {            if (nums[i] != nums[i - 1])            {                return nums[i - 1];            }        }        return nums[nums.Length - 1];    }}

137.137-Single Number II-Difficulty: Medium

Given an array of integers, every element appearsthree times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

思路

和上题相同,重复数目换成了三个

依旧先sort,然后再找,返回的永远是i-2

public class Solution {    public int SingleNumber(int[] nums) {                Array.Sort(nums);        for (int i = 2; i < nums.Length; i += 3)        {            if (nums[i - 1] != nums[i - 2])            {                return nums[i - 2];            }        }        return nums[nums.Length - 1];    }}


138.138-Copy List with Random Pointer-Difficulty: Hard

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

思路

深度复制一个链表,其中包括一个随机的节点

运用哈希表,过去的节点作为key,新节点作为value,匹配random

两遍遍历,先把所有next深复制一遍,全部存在哈希里,然后第二遍遍历匹配哈希复制random

/** * Definition for singly-linked list with a random pointer. * public class RandomListNode { *     public int label; *     public RandomListNode next, random; *     public RandomListNode(int x) { this.label = x; } * }; */public class Solution {    public RandomListNode CopyRandomList(RandomListNode head) {//运用哈希表,过去的节点作为key,新节点作为value,匹配random      if (head == null)            return null;        RandomListNode new_head = new RandomListNode(head.label);        RandomListNode new_head_temp = new_head;        RandomListNode temp = head;        Hashtable hash = new Hashtable();        hash.Add(head, new_head);        while (temp.next != null)        {            new_head_temp.next = new RandomListNode(temp.next.label);            hash.Add(temp.next, new_head_temp.next);            new_head_temp = new_head_temp.next;            temp = temp.next;        }        temp = head;        new_head_temp = new_head;        while (temp != null)        {            if (temp.random != null)                new_head_temp.random = (RandomListNode)hash[temp.random];            new_head_temp = new_head_temp.next;            temp = temp.next;        }        return new_head;    }}




















0 0
原创粉丝点击