LC 905 && 824 && 146 && 268

LC 905 : Sort Array By Parity

Description:

Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.

You may return any answer array that satisfies this condition.

Example 1:

Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

Note:

1 <= A.length <= 5000
0 <= A[i] <= 5000

Solution:

public int[] sortArrayByParity(int[] A) {
        int[] ans = new int[A.length];
        int t = 0;

        int low = 0, high = A.length - 1;

        for (int i = 0; i < A.length; ++i) {
            if (A[i] % 2 ==0) 
                ans[low++] = A[i];
            else 
                ans[high--] = A[i];
        }

        return ans;
    }

LC 824 Goat Latin

Description:

A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.

We would like to convert the sentence to “Goat Latin” (a made-up language similar to Pig Latin.)

The rules of Goat Latin are as follows:

If a word begins with a vowel (a, e, i, o, or u), append “ma” to the end of the word.
For example, the word ‘apple’ becomes ‘applema’.

If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add “ma”.
For example, the word “goat” becomes “oatgma”.

Add one letter ‘a’ to the end of each word per its word index in the sentence, starting with 1.
For example, the first word gets “a” added to the end, the second word gets “aa” added to the end and so on.
Return the final sentence representing the conversion from S to Goat Latin.

Example 1:

Input: “I speak Goat Latin”
Output: “Imaa peaksmaaa oatGmaaaa atinLmaaaaa”
Example 2:

Input: “The quick brown fox jumped over the lazy dog”
Output: “heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa”

Solution:

public String toGoatLatin(String S) {
        Set<Character> set = new HashSet<>();
        set.add('a'); set.add('e'); set.add('i'); set.add('o'); set.add('u');
        set.add('A'); set.add('E'); set.add('I'); set.add('O'); set.add('U');
        // 1 represents the vowel ; 2 represents the consonant
        int flag = 0; char tem = ' '; int index = 1;

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < S.length(); ++i) {
            if (S.charAt(i) == ' ' || i == S.length() - 1) {
                if (i == S.length() - 1)
                    sb.append(S.charAt(i));
                if (flag == 2)
                    sb.append(tem);
                flag = 0;
                sb.append("ma");
                for(int j = 1; j <= index; ++j)
                    sb.append('a');
                index++;
                if (i != S.length() - 1)
                    sb.append(" ");
            } else {
                if (flag == 0) {
                    if (set.contains(S.charAt(i))) {
                        flag = 1;
                    } else {
                        flag = 2;
                        tem = S.charAt(i);
                    }
                    sb.append(flag == 1 ? S.charAt(i) : "");
                    continue;
                } 
                sb.append(S.charAt(i));
            }
        }
        return sb.toString();
    }

LC 146. LRU Cache

Description:

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

The cache is initialized with a positive capacity.

Follow up:
Could you do both operations in O(1) time complexity?

Example:

LRUCache cache = new LRUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4

Solution:

follow up说用O1 时间复杂度
肯定就想到hashmap
又考虑到普通链表是单向的,所以删除操作不是O1时间复杂度。但是双向链表是O1的删除时间复杂度。
所以用hashmap来储存每个node的位置信息,可以O1来获取,同时能O1来删除,并且设置一个尾巴指针来实现O1放入链表尾巴。


private static class Dequeue {
        Dequeue next, prev;
        int value, key;
        public Dequeue (int key, int value) {
            this.key = key;
            this.value = value;
        }
    }
    
    Dequeue head = null, tail = null;
    HashMap<Integer, Dequeue> cache = null;
    int capacity = 0;

    public LRUCache(int capacity) {
        cache = new HashMap<Integer, Dequeue>();
        this.capacity = capacity;
        initializeDequeue();
    }
    
    public void initializeDequeue() {
        head = new Dequeue(-1, -1);
        tail = new Dequeue(-1, -1);
        head.next = tail;
        tail.prev = head;
    }

    public int get(int key) {
        Dequeue node = cache.get(key);
        if (node == null)
            return -1;
        delete(node);
        insertAtLast(node);
        return node.value;
    }

    public void put(int key, int value) {
        if (cache.containsKey(key)) {
            Dequeue node = cache.get(key);
            node.value = value;
            node.key = key;
            delete(node);
            insertAtLast(node);
        } else {
            if (cache.size() == capacity) {
                int keyToRemove = deleteLeastRecentlyUsed();
                cache.remove(keyToRemove);
            }
            Dequeue node = new Dequeue(key, value);
            insertAtLast(node);
            cache.put(key, node);
        }
    }

    private void delete(Dequeue node) {
        Dequeue prev = node.prev;
        Dequeue next = node.next;
        prev.next = next;
        next.prev = prev;
    }
    
    private void insertAtLast(Dequeue node) {
        Dequeue prev = tail.prev;
        prev.next = node;
        node.prev = prev;
        node.next = tail;
        tail.prev = node;
    }
    
    private int deleteLeastRecentlyUsed() {
        Dequeue node = head.next;
        head.next = node.next;
        node.next.prev = head;
        node.next = null;
        node.prev = null;
        return node.key;
    }	

LC 268. Missing Number

Description:

Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.

Example 1:

Input: [3,0,1]
Output: 2
Example 2:

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

Solution:

又是妈问跪 系列。
妈妈问我为啥跪着看代码。

public int missingNumber(int[] nums) {
        int len = nums.length;
        for (int i = 0; i < nums.length; ++i) {
            len ^= i ^ nums[i];
        }
        return len;
    }

举个例子:
数组为 0 1 2 4 少的是 2
Index 0 1 2 3
Value 0 1 3 4

按照代码思路,len 经过操作后等价于如下所示:用了异或交换律

=4∧(0∧0)(1∧1)(2∧3)(3∧4)
=(4∧4)(0∧0)(1∧1)(3∧3)∧2
=0∧0∧0∧0∧2
=2


Solution2:
还有同样很快也牛逼的高斯定理:

把所有数加一遍 减去 目标值 = 漏掉的数字。。。


public int missingNumber(int[] nums) {
        int sum = 0;
        for(int i = 0; i < nums.length; ++i) 
            sum += (i - nums[i]);
        return (sum + nums.length);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值