面试笔试杂项积累-leetcode 166-170

来源:互联网 发布:表达无网络的图片大全 编辑:程序博客网 时间:2024/05/29 09:57

168.168-Excel Sheet Column Title-Difficulty: Easy

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

    1 -> A    2 -> B    3 -> C    ...    26 -> Z    27 -> AA    28 -> AB 
参考:

https://leetcode.com/discuss/82531/my-easy-to-understand-java-solution

public class Solution {    public string ConvertToTitle(int n) {        string res = "";        while (n != 0)        {            char ch = (char)((n - 1) % 26 + 65);            n = (n - 1) / 26;            res = ch + res;        }        return res;    }}

169.169-Majority Element-Difficulty: Easy

Given an array of size n, find the majority element. The majority element is the element that appears more than⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

方法一

思路

找到数组中重复次数超过n/2的数

博主使用哈希表做的,key为匹配数值,value为次数,时间复杂度O(2n),空间O(n)

public class Solution {    public int MajorityElement(int[] nums) {               Hashtable hash = new Hashtable();        for (int i = 0; i < nums.Length; i++)        {            if (hash.ContainsKey(nums[i]))                hash[nums[i]] = (int)hash[nums[i]] + 1;            else                hash.Add(nums[i],1);        }        int max = 0;        int temp = 0;        for (int i = 0; i < nums.Length; i++)        {            if (max < (int)hash[nums[i]])            { max = (int)hash[nums[i]]; temp = nums[i]; }        }        return temp;    }}

方法二

思路

参考:

https://leetcode.com/discuss/83205/java-o-n-time-o-1-space-optimal-solution

时间复杂度O(n),空间O(1)


public class Solution {    public int majorityElement(int[] nums) {        int candidate = 0;        int count = 0;        for (int num : nums) {            if (count == 0) {                candidate = num;                count++;            } else if (candidate == num) {                count++;            } else {                count--;            }        }        return candidate;    }}


















1 0
原创粉丝点击