面试笔试杂项积累-leetcode 226-230

226.226- Implement Stack using Queues-Difficulty: Easy

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9
to
     4
   /   \
  7     2
 / \   / \
9   6 3   1
Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

思路

所有左右节点都反过来

先序遍历然后反过来即可

上面那段话就不译了,,,,总之,基础都掌握不好,何谈就业

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode InvertTree(TreeNode root) {
                if (root == null)
            return root;
   printTree(root);
        return root;
    }
    void printTree(TreeNode root)
    {
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;

        if (root.left != null)
            printTree(root.left);
        if (root.right != null)
            printTree(root.right);

    }
}

227.227-Basic Calculator II-Difficulty: Medium

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5

方法一

思路

224题的加强版。没有了括号,运算符变成了+-*/

把乘除先做了,当然+,-还是使乘除的结果带上正负,把结果存到栈里,最后加在一起即可

public class Solution {
    public int Calculate(string s) {
             int len;
        if (s == null || (len = s.Length) == 0) return 0;
        Stack<int> stack = new Stack<int>();
        int num = 0;
        char sign = '+';
        for (int i = 0; i < len; i++)
        {
            if (char.IsDigit(s[i]))
            {
                num = num * 10 + s[i] - '0';
            }
            if ((!char.IsDigit(s[i]) && ' ' != s[i]) || i == len - 1)
            {
                if (sign == '-')
                {
                    stack.Push(-num);
                }
                if (sign == '+')
                {
                    stack.Push(num);
                }
                if (sign == '*')
                {
                    stack.Push(stack.Pop() * num);
                }
                if (sign == '/')
                {
                    stack.Push(stack.Pop() / num);
                }
                sign = s[i];
                num = 0;
            }
        }

        int re = 0;
        foreach (int i in stack)
        {
            re += i;
        }
        return re;
    }
}

方法二

思路

又在discuss上发现了一个不需要额外数据结构辅助的方法

参考:

https://leetcode.com/discuss/42643/my-16-ms-no-stack-one-pass-short-c-solution

class Solution {
public:
    int calculate(string s) {
        int result = 0, cur_res = 0;
        char op = '+';
        for(int pos = s.find_first_not_of(' '); pos < s.size(); pos = s.find_first_not_of(' ', pos)) {
            if(isdigit(s[pos])) {
                int tmp = s[pos] - '0';
                while(++pos < s.size() && isdigit(s[pos]))
                    tmp = tmp*10 + (s[pos] - '0');
                switch(op) {
                    case '+' : cur_res += tmp; break;
                    case '-' : cur_res -= tmp; break;
                    case '*' : cur_res *= tmp; break;
                    case '/' : cur_res /= tmp; break;
                }
            }
            else {
                if(s[pos] == '+' || s[pos] == '-') {
                    result += cur_res;
                    cur_res = 0;
                }
                op = s[pos++];
            }
        }
        return result + cur_res;
    }
};

228.228-Summary Ranges-Difficulty: Easy

Given a sorted integer array without duplicates, return the summary of its ranges.

For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].

思路

两个指针 start, end.  如果nums[end+1] = nums[end]+1, 就移动end指针, 否则, 插入字符串nums[start]->nums[end].

注意如果不符合情况并且start == end就保留(存入list)该数字,再进行下一个判断

public class Solution {
    public IList<string> SummaryRanges(int[] nums) {
    int start = 0;
        int end = 0;
        IList<string> fin = new List<string>();
        while (end < nums.Length)
        {
            if (start == end && end == nums.Length - 1)
            {
                fin.Add(nums[end].ToString()); break;
            }
            if (nums[end + 1] == nums[end] + 1)
            {
                ++end;
                if (end == nums.Length - 1)
                {
                    fin.Add(nums[start] + "->" + nums[end]);
                    break;
                }
            }
            else
            {
                if (start == end)
                {
                    fin.Add(nums[end].ToString());
                    ++end; ++start;
                }
                else
                {
                    fin.Add(nums[start] + "->" + nums[end]);
                    start = end + 1;
                    ++end;
                    continue;
                }
            }

        }
        return fin;
    }
}

229.229-Majority Element II-Difficulty: Easy

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

Hint:

How many majority elements could it possibly have?

思路

169题的加强版

169题是存在重复数多余n/2,这回是多余n/3的都要,就有可能是一个数或两个数。

我们用hash表来解决,key为该数的值,value为个数,超过n/3就存入结果list

public class Solution {
    public IList<int> MajorityElement(int[] nums) {
                Hashtable hash = new Hashtable();
        IList<int> list = new List<int>();
        int fin = nums.Length / 3;
        for (int i = 0; i < nums.Length; i++)
        {
            if (list.Contains(nums[i]))
                continue;
            if (hash.ContainsKey(nums[i]))
            {

                hash[nums[i]] = (int)hash[nums[i]] + 1;
               if ((int)hash[nums[i]] > fin)
                    list.Add(nums[i]);
            }
            else
              {
                  hash.Add(nums[i], 1);
                if (1 > fin)
                    list.Add(nums[i]);
            }
        }

        return list;
    }
}

230.230-Kth Smallest Element in a BST-Difficulty: Medium

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

Hint:

  1. Try to utilize the property of a BST.
  2. What if you could modify the BST node's structure?
  3. The optimal runtime complexity is O(height of BST).

思路

找到在二叉搜索树中第k小的节点

看了一个hint,想到了二叉搜索树的性质,中序遍历有顺序啊,,故如此解决


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
  int count = 0;
    int fin = 0;
    int _k = 0;
    public int KthSmallest(TreeNode root, int k)
    {
        _k = k;
        printNode(root);
        return fin;
    }
    public void printNode(TreeNode root)
    {
        if (root.left != null)
            printNode(root.left);
        ++count;
        if (count == _k)
        {
            fin = root.val;
            return;
        }
        if (root.right != null)
            printNode(root.right);
    }
}









  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值