leetcode easy - Contains Duplicate

 LeetCode


Code
class Solution {
    public boolean containsDuplicate(int[] nums) {
        Arrays.sort(nums);


        for ( int i = 0; i < nums.length-1; i++ ) {
            if (nums[i] == nums[i+1]) return true;
        }


        return false;
    }

leetcode easy - Pascal's Triangle

LeetCode

Code

import java.util.ArrayList;
import java.util.List;


class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> result = new ArrayList<>();
        for ( int i = 0; i < numRows; i++ ) {
            List<Integer> row = new ArrayList<>();
            for ( int j = 0; j <= i; j++ ) {
                if (i == 0 || i == 1 || j == 0 || i == j) {
                    row.add(1);
                    continue;
                }


                System.out.println("(" + i + "," + j + ")");
                row.add(result.get(i-1).get(j-1) + result.get(i-1).get(j));
            }
            result.add(row);
        }
        return result;
    }


leetcode medium - Number of Islands

 Leetcode


Code
class Solution {
    public int numIslands(char[][] grid) {

        int count = 0;

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == '1') {
                    count++;
                    clearIsland(grid, i, j);
                }
            }
        }
        return count;
    }

    private void clearIsland(char[][] grid, int i, int j) {
        if (i < 0 || j < 0 || i >= grid.length || j >= grid[i].length || grid[i][j] == '0') return;


        grid[i][j] = '0';
        clearIsland(grid, i, j-1); // up
        clearIsland(grid, i, j+1); // down
        clearIsland(grid, i-1, j); // left
        clearIsland(grid, i+1, j); // right
    }

leetcode medium - LRU Cache

LeetCode

Code
It will be great to implement LinkedList by myself, I use JDK LinkedList directly

class LRUCache {

    private LinkedList<Integer> list = new LinkedList<>();
    private Map<Integer, Integer> map = new HashMap<>();
    private final int cap;


    public LRUCache(int capacity) {
        this.cap = capacity;
    }


    public int get(int key) {
        Integer result = map.get(key);
        if (result == null) {
            return -1;
        } else {
            list.remove(Integer.valueOf(key));
            list.addFirst(key);
        }
        return result;
    }


    public void put(int key, int value) {
        Integer result = map.get(key);
        if (result != null) {
            list.remove(Integer.valueOf(key));
        } else {
            if (map.size() == cap) {
                map.remove(list.removeLast());
            }
        }
        list.addFirst(key);
        map.put(key, value);
     }

java.lang.ref


  1. SoftReference: Cleared when GC is response to memory demand. Often used to implement memory-sensitive cache.
  2. WeakReference: Don’t prevent to be finalized. Often used to implement canonicalizing mapping. (Mapping only reachable object instances)
  3. PhantomReference: Are enqueued after determining to be reclaimed. Not automatically cleared by GC. Object referenced via phantom reference won’t be cleared by GC automatically until phantom reference cleared. 

LeetCode - Kids With the Greatest Number of Candies

 

LeetCode

Code
class Solution {
    public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
        int max = max(candies);
        List<Boolean> result = new ArrayList<>();
        for (int i = 0; i < candies.length; i++) {
            result.add(candies[i] + extraCandies >= max);
        }
        return result;
    }
    
    private int max(int[] candies) {
        int max = 0;
        for ( int i = 0; i < candies.length; i++ ) {
            if (max < candies[i]) {
                max = candies[i];
            }
        }
        return max;
    }
}

leetcode - Shuffle the Array

 

LeetCode

Code
class Solution {
    public int[] shuffle(int[] nums, int n) {
        int[] result = new int[nums.length];
        int currentIdx = 0;
        for (int i = 0; i < n; i++) {
            result[currentIdx] = nums[i];
            result[currentIdx+1] = nums[i+n];
            currentIdx += 2;
        }
        return result;
    }
}

leetcode - Running Sum of 1d Array

 

LeetCode

Code
class Solution {
    public int[] runningSum(int[] nums) {
        int[] result = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            if (i == 0) {
                result[i] = nums[i];
            } else {
                result[i] = result[i-1] + nums[i];
            }
        }
        return result;
    }
}

Spring Data Reactive Cassandra CRUD

 Git branch


Cassandra commands
sudo docker run --name test-cassandra -p 9042:9042 -d cassandra:latest
sudo docker run --name test-cassandra-2 --link test-cassandra:cassandra -d cassandra:latest

docker exec -it test-cassandra /bin/bash

cqlsh> CREATE KEYSPACE test WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 3 } AND DURABLE_WRITES = false;

cqlsh> use test;

cqlsh:test> CREATE TABLE person ( id text PRIMARY KEY, name text );

Person.java
@Data
public class Person {

    @PrimaryKey private String id;
    private String name;

}

ReactivePersonRepository.java
public interface ReactivePersonRepository extends ReactiveCassandraRepository<Person, String> {}

ReactivePersonService.java
@Service
public class ReactivePersonService {

    @Autowired
    private ReactivePersonRepository reactivePersonRepository;

    public Mono<Person> save(Person person) {
        return reactivePersonRepository.save(person);
    }

    public Mono<Person> findById(String id) {
        return reactivePersonRepository.findById(id);
    }

    public Flux<Person> findAll() {
        return reactivePersonRepository.findAll();
    }

    public Mono<Void> deleteById(String id) {
        return reactivePersonRepository.deleteById(id);
    }

    public Mono<Void> deleteAll() {
        return reactivePersonRepository.deleteAll();
    }

}

ReactivePersonController.java
@RestController
@RequestMapping("/api/v2/")
public class ReactivePersonController {

    @Autowired
    private ReactivePersonService reactivePersonService;

    @PostMapping(value = "/person", consumes = "application/json")
    public Mono<Person> createPerson(@RequestBody Person person) {
        System.out.println("create person" + person);
        person.setId(UUID.randomUUID().toString());
        return reactivePersonService.save(person);
    }

    @GetMapping(value = "/person")
    public Mono<Person> getPerson(@RequestParam String id) {
        return reactivePersonService.findById(id);
    }

    @GetMapping(value = "/persons")
    public Flux<Person> getAllPersons() {
        return reactivePersonService.findAll();
    }

    @DeleteMapping("/person/{id}")
    public Mono<Void> deletePerson(@PathVariable String id) {
        return reactivePersonService.deleteById(id);
    }

    @DeleteMapping("/persons")
    public Mono<Void> deleteAll() {
        return reactivePersonService.deleteAll();
    }

express.js - body-parser - specific uri

 

Commit

code
var express = require('express');
var bodyParser = require('body-parser')
var app = express()
    .use( '/test', bodyParser() ).use(function (req, res) {
        console.log("body", req.body)
        console.log("foo", req.body.foo)
        res.send(req.body)
    })
    .listen(3000);

execute
$ node app.js

curl
$ curl -s  http://127.0.0.1:3000/test/  -H "content-type: application/json" -d   "{\"foo\":123}"
{"foo":123}

別名演算法 Alias Method

 題目 每個伺服器支援不同的 TPM (transaction per minute) 當 request 來的時候, 系統需要馬上根據 TPM 的能力隨機找到一個適合的 server. 雖然稱為 "隨機", 但還是需要有 TPM 作為權重. 解法 別名演算法...