面试笔试杂项积累-leetcode 16-20

16.16-3Sum Closest-Difficulty: Medium

Given an array S of n integers, find three integers inS such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

思路

本题与上一道3sum差不多,解法也差不多,是求在一个数组中三位数之和与给定数字最相近,返回三位数之和。

博主开始看题时又天真的想用三循环了,果然又超时,O(n^3)。。

和上一道题大题解法相同,都是一个循环中再two pointers遍历,然后就没问题了

千万不要手欠加上某些想当然的判断条件啊。。。加上之后全删了,总有你想不到的数组啊。。。。。。

public class Solution {
    public int ThreeSumClosest(int[] nums, int target) {
  if (nums.Length < 3)
            return 0;
        Array.Sort(nums);
        if (nums.Length == 3)
            return nums[0] + nums[1] + nums[2];
        int sum = nums[0] + nums[1] + nums[2];
        int temp1 = 0;
        int temp2 = 0;
        for (int i = 0; i < nums.Length - 2; i++)
        {
            int start = i + 1;
            int end = nums.Length - 1;
            while (start < end)
            {
                temp1 = Math.Abs(target - (nums[start] + nums[end] + nums[i]));
                temp2 = Math.Abs(target - sum);
                if (temp1 == 0)
                    return target;
                if (temp1 < temp2)
                {
                    sum = nums[start] + nums[end] + nums[i];
                }
                    if ((nums[start] + nums[end] + nums[i]) < target)
                    {
                        start++;
                    }
                    else if ((nums[start] + nums[end] + nums[i]) > target)
                    {
                        end--;
                    }
            }
        }
        return sum;
    }
}

17.17-Letter Combinations of a Phone Number-Difficulty: Medium

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.


思路

模拟输入法功能,输入一串数字,给出数字代表的所有可能的字母组合(有顺序),Difficulty Distribution 上写的需要利用DFS,总之还是离不开递归

出现了在固定次序遍历字符重复问题,最后通过赋值新string前,把temp裁到需要的大小再赋值,问题解决

改善

1.消除了一个不需要的两行代码判断和temp清空,居然节省了近40ms,震惊

2.改善了存储映射字母的数据结构,开始用的char的二维锯齿数组,之后甚觉浪费,而且占代码行数太多遂改为string一维数组,看着舒服多了,并节省10ms+

public class Solution {
        string temp = "";
    IList<string> fin = new List<string>();
     string[] sample = new string[8] { "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
    public IList<string> LetterCombinations(string digits) {
        recursion( digits, 0);
        return fin;
    }
    void recursion( string message, int num)
    {
        if (num < message.Length)
            for (int i = 0; i < sample[int.Parse(message[num].ToString()) - 2].Length; i++)
            {
                temp = temp.Substring(0, num);
                temp += sample[int.Parse(message[num].ToString()) - 2][i];
                if (num == message.Length - 1)
                {
                    fin.Add(temp);
                }
                recursion(message, num + 1);
            }
    }
}

18.18-4Sum-Difficulty: Medium

Given an array S of n integers, are there elementsa,b, c, and d in S such that a +b +c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie,abcd)
  • The solution set must not contain duplicate quadruplets.
    For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

    A solution set is:
    (-1,  0, 0, 1)
    (-2, -1, 1, 2)
    (-2,  0, 0, 2)

思路

本题依旧k-sum问题,与3sum差不多,开始播主以为该使用四个pointers,测试了一下丢失部分结果,后来看别人有依旧用two pointers,两个循环也通过了,估计这种方法会浪费大量时间,其中可以使用hash法来避免重复值

参考:

http://www.cnblogs.com/etcow/archive/2012/06/15/2548739.html

public class Solution {
    public IList<IList<int>> FourSum(int[] nums, int target) {
 List<IList<int>> ret = new List<IList<int>>();
        if (nums.Length < 4)
            return ret;

        Array.Sort(nums);
        string str;
        Dictionary<string, bool> map = new Dictionary<string, bool>();

        for (int a = 0; a <= nums.Length - 4; a++)
        {
            for (int b = a + 1; b <= nums.Length - 3; b++)
            {
                int c = b + 1;
                int d = nums.Length - 1;
                while (c < d)
                {
                    if (nums[a] + nums[b] + nums[c] + nums[d] == target)
                    {
                        str = nums[a].ToString() + nums[b].ToString() + nums[b].ToString() + nums[c].ToString();
                        if (map.ContainsKey(str))
                        {
                            c++;
                            d--;
                        }
                        else
                        {
                            List<int> quadruplet = new List<int> { nums[a], nums[b], nums[c], nums[d] };
                            map.Add(str, true);
                            ret.Add(quadruplet);
                            c++;
                            d--;
                        }
                    }
                    else if (nums[a] + nums[b] + nums[c] + nums[d] < target)
                        c++;
                    else
                        d--;
                }
            }
        }

        return ret;
    }
}

19.19-Remove Nth Node From End of List-Difficulty: Easy

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

思路

很简单的一道题,给一个链表的头结点,返回指定从后往前删去第几个节点后的头结点。博主粗心开始以为从前往后的序列,结果又重来,不过确实很简单,不必多言

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
        public ListNode RemoveNthFromEnd(ListNode head, int n)
        {
              if (head == null)
            return null;
        int max = 0;
        ListNode temp_node = head;
        while (temp_node != null)
        {
            temp_node = temp_node.next;
            ++max;
        ]
        if (n > max || n < 0)
            return null;
        if (n == max)
            if (head.next != null)
                return head.next;
            else
                return null;
        temp_node = head;
        if (head.next == null)
            return null;
        for (int i = 1; i < max - n ; i++)
        {
            temp_node = temp_node.next;
        }
        temp_node.next = temp_node.next.next;
        return head;
        }
}

20.20-Valid Parentheses-Difficulty: Easy

Given a string containing just the characters '(', ')', '{', '}', '[' and']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

思路

匹配括号的题自然是要用栈啦(笑),但是不知道题中的括号有没有嵌套,比如(([]))这样,还是单纯的{}[](),不过怎样都可以用栈轻松搞定,

博主没有建立栈这个数据结构,而是用一个int数组模拟栈后入先出的行为。一次通过,いいよ

public class Solution {
    public bool IsValid(string s) {
            int[] stack = new int[s.Length];
        int temp = 0;
        for (int i = 0; i < s.Length; i++)
        {
            switch (s[i].ToString())
            {
                case "(":
                    stack[temp] = 0;
                    ++temp;
                    break;
                case "[":
                    stack[temp] = 2;
                    ++temp;
                    break;
                case "{":
                    stack[temp] = 3;
                    ++temp;
                    break;
                case ")":
                    if (temp <= 0)
                        return false;
                    if (stack[temp-1] == 0)
                        --temp;
                    else
                        return false;
                    break;
                case "]":
                    if (temp <= 0)
                        return false;
                    if (stack[temp-1] == 2)
                        --temp;
                    else
                        return false;
                    break;
                case "}":
                    if (temp <= 0)
                        return false;
                    if (stack[temp-1] == 3)
                        --temp;
                    else
                        return false;
                    break;
            }
        }
        if (temp != 0)
            return false;
        else
            return true; 
    }
}











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值