面试笔试杂项积累-leetcode 31-35

31.31-Next Permutation-Difficulty:Medium

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,31,3,2
3,2,11,2,3
1,1,51,5,1

思路

全排列问题,在原数组中返回下一个全排列的数组

参考:

http://blog.csdn.net/ljiabin/article/details/41956813

public class Solution {
    public void NextPermutation(int[] nums) {
         //1.找到最后一个升序位置pos  
        int pos = -1;
        for (int i = nums.Length - 1; i > 0; i--)
        {
            if (nums[i] > nums[i - 1])
            {
                pos = i - 1;
                break;
            }
        }
        //2.如果不存在升序,即这个数是最大的,那么反排这个数组  
        if (pos < 0)
        {
            Array.Reverse(nums, 0, nums.Length );
            return;
        }
        //3.存在升序,那么找到pos之后最后一个比它大的位置  
        for (int i = nums.Length - 1; i > pos; i--)
        {
            if (nums[i] > nums[pos])
            {
                int tmp = nums[i];
                nums[i] = nums[pos];
                nums[pos] = tmp;
                break;
            }
        }
        Array.Reverse(nums, pos + 1, nums.Length-pos - 1);
    }
}

32.32-Longest Valid Parentheses-Difficulty:Hard

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is"()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is"()()", which has length = 4.

方法一

思路

题目要求返回最长连续可行的括号length,存在嵌套。

博主的方法,运行时间140ms,时间复杂度O(3n)

之前几道题也出现了匹配括号的问题,不用想了,绝对是用栈。

博主用一个int数组来模拟栈的行为。用一个bool数组来记录当前位置的括号是否有搭配,有搭配则为true。再在后面循环求出连续最多的true的数目,即是最后答案。

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

方法二

思路

时间复杂度(n),运行时间132ms

用一个数l来记录开始不匹配的位置,后来每匹配一个,与之前的长度比较,留下最大长度。

参考:

http://blog.csdn.net/makuiyu/article/details/43501333

public class Solution {
    public int LongestValidParentheses(string s) {
      int res = 0, l = 0;

               Stack<int> si = new Stack<int>();
        for (int i = 0; i < s.Length; ++i)
        {
            if (s[i] == '(')
                si.Push(i);
            else
            {
                if (si.Count == 0)
                    l = i + 1;
                else
                {
                    si.Pop();
                    if (si.Count == 0)
                        res = Math.Max(res, i - l + 1);
                    else
                        res = Math.Max(res, i - si.Peek());
                }
            }
        }
        return res;
    }
}

方法三

思路

使用DP方法,时间复杂度(n),运行时间128ms

代码界的抽象艺术= =。。。

参考:

https://leetcode.com/discuss/8092/my-dp-o-n-solution-without-using-stack

public class Solution {
    public int LongestValidParentheses(string s) {
        if (s.Length <= 1) return 0;
        int curMax = 0;
        int[] longest = new int[s.Length];
        for (int i = 1; i < s.Length; i++)
        {
            if (s[i] == ')' && i - longest[i - 1] - 1 >= 0 && s[i - longest[i - 1] - 1] == '(')
            {
                longest[i] = longest[i - 1] + 2 + ((i - longest[i - 1] - 2 >= 0) ? longest[i - longest[i - 1] - 2] : 0);
                curMax = Math.Max(longest[i], curMax);
            }
        }
        return curMax;
    }
}

33.33-Search in Rotated Sorted Array-Difficulty:Hard

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

方法一

思路

题目要求返回数组中与target相同所在index即可,如不存在则返回-1,数组为排序后旋转了的数组.

博主开始以为要返回排序后的序列,代码编完自己测试是没有问题= =。。。 这个最简单的查找就能通过

 public int Search(int[] nums, int target) {
        for(int i = 0; i < nums.Length; i ++)
        {
            if(nums[i] == target)
                return i;
        }
        return -1;

方法二

思路

two points方法

参考:

http://blog.csdn.net/ljiabin/article/details/40453607

 public int Search(int[] nums, int target) {
         int l = 0;
        int r = nums.Length - 1;
        while (l <= r)
        {
            int mid = (l + r) / 2;
            if (target == nums[mid]) return mid;
            if (nums[l] <= nums[r])
            {
                if (target < nums[mid]) r = mid - 1;
                else l = mid + 1;
            }
            else if (nums[l] <= nums[mid])
            {
                if (target > nums[mid] || target < nums[l]) l = mid + 1;
                else r = mid - 1;
            }
            else
            {
                if (target < nums[mid] || target > nums[r]) r = mid - 1;
                else l = mid + 1;
            }
        }
        return -1;
    }

34.34-Search for a Range-Difficulty:Medium

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

思路

给一个排好序的数组(默认从小到大)找到给定target开始出现的index,和最后的index。该index是程序员的index(从0开始),很简单,遍历即可

public class Solution {
    public int[] SearchRange(int[] nums, int target) {
           int[] temp = new int[2]{-1,-1};

        for (int i = 0; i < nums.Length; i++)
        { 
        if(nums[i] == target)
        {
            temp[0] = i;
            ++i;
            while (i < nums.Length)
            {
                if (nums[i] != target)
                {
                    temp[1] = i-1;
                    return temp;
                }
                i++;
            }
            temp[1] = i - 1;
        }
        
        
        }
            return temp;
    }
}

35.35-Search Insert Position-Difficulty:Medium

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

思路

给一个排好序的数组(默认从小到大),找到与给定target相同的数的index,如没有相同,则返回target该插入该数组中的位置。同样是遍历,很简单。

public class Solution {
    public int SearchInsert(int[] nums, int target) {
                int i = 0;
        for (; i < nums.Length; i++)
        {
            if (nums[i] >= target)
                break;
        }
            return i;
    }
}










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值