iT邦幫忙

2021 iThome 鐵人賽

DAY 5
0
AI & Data

想到甚麼打甚麼系列 第 5

找LeetCode上簡單的題目來撐過30天啦(DAY5)

  • 分享至 

  • xImage
  •  

今天值接上菜,不閒聊

今日小菜
題號:182 標題:Duplicate Emails 難度:Easy

SQL Schema
Write a SQL query to find all duplicate emails in a table named Person.

For example, your query should return the following for the above table:

Note: All emails are in lowercase.

我的SQL指令

select Email from (select Email,count(*) c from Person group by Email ) as table1 where table1.c>1

今日主菜
題號:169 標題:Majority Element 難度:Easy

Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

Example 1:
Input: nums = [3,2,3]
Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2]
Output: 2

Constraints:
• n == nums.length
• 1 <= n <= 5 * 104
• -231 <= nums[i] <= 231 - 1

我的程式碼

import java.util.HashMap;

class Solution {
    public int majorityElement(int[] nums) {
        HashMap<Integer,Integer> temp = new HashMap<Integer, Integer>();
        int l = nums.length,i,j,max=0,vmax=0;
        //System.out.print(l);
        for(i=0;i<l;i++){
     

            if(temp.containsKey(nums[i])){
                temp.replace(nums[i], temp.get(nums[i])+1) ;
   
            }else{
                temp.put(nums[i],1);
            }
        }
        Set s =temp.keySet();
        //System.out.println(temp);

         for(Object key : s){
            if(temp.get(key)>vmax){
                 max = (int)key;
                 vmax = temp.get(key);
                //System.out.println(key + ","+temp.get(key));
            }
        }
        
        return max;
    }
}

邏輯
用HashMap,把出現過的值當key,次數當value,再去尋找value最大得時後,key是多少

這題花費比較久的時間
在HashMap,上次聽大神(it邦可憐小菜鳥不能發文)說有這個東西(HashMap)可以用,剛好選到這一題,就來試試看了


DAY5心得
沒有心得,繼續去拚題目存庫存去


上一篇
找LeetCode上簡單的題目來撐過30天啦(DAY4)
下一篇
找LeetCode上簡單的題目來撐過30天啦(DAY6)
系列文
想到甚麼打甚麼30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言