Coding-- small practice

Fifth, find treasure

 

You have a map that marks the location of a treasure island. Some of the map area has jagged rocks and dangerous reefs. Other areas are safe to sail in. There are other explorers trying to find the treasure. So you must figure out a shortest route to the treasure island.

 

 Assume the map area is a two dimensional grid, represented by a matrix of characters. You must start from the top-left corner of the map and can move one block up, down, left or right at a time. The treasure island is marked as X in a block of the matrix. X will not be at the top-left corner. Any block with dangerous rocks or reefs will be marked as D. You must not enter dangerous blocks. You cannot leave the map area. Other areas O are safe to sail in. The top-left corner is always safe. Output the minimum number of steps to get to the treasure.

 

 

Example:

 

Input:
[['O', 'O', 'O', 'O'], ['D', 'O', 'D', 'O'], ['O', 'O', 'O', 'O'], ['X', 'D', 'D', 'O']] Output: 5 Explanation: Route is (0, 0), (0, 1), (1, 1), (2, 1), (2, 0), (3, 0) The minimum route takes 5 steps.

This question I was thinking that there is no, then later see the answer, debug with it again, with some ideas, later encounter, to have a forward direction of the.

Answer:

 1 public class Demo{
 2     private static final int[][] DIRS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
 3     
 4     public static int minSteps(char[][] grid) {
 5         Queue<Point> q = new ArrayDeque<>();
 6         q.add(new Point(0, 0));
 7         grid[0][0] = 'D'; // mark as visited
 8         for (int steps = 1; !q.isEmpty(); steps++) {
 9             for (int sz = q.size(); sz > 0; sz--) {
10                 Point p = q.poll();
11             
12                 for (int[] dir : DIRS) {
13                     int r = p.r + dir[0];
14                     int c = p.c + dir[1];
15                     
16                     if (isSafe(grid, r, c)) {
17                         if (grid[r][c] == 'X') return steps;
18                         grid[r][c] = 'D';
19                         q.add(new Point(r, c));
20                     }
21                 }
22             }
23         }
24         return -1;
25     }
26     
27     private static boolean isSafe(char[][] grid, int r, int c) {
28         return r >= 0 && r < grid.length && c >= 0 && c < grid[0].length && grid[r][c] != 'D';
29     }
30     
31     private static class Point {
32         int r, c;
33         Point(int r, int c) {
34             this.r = r;
35             this.c = c;
36         }
37     }
38     
39     public static void main(String[] args) {
40         char[][] grid = {{'O', 'O', 'O', 'O'},
41                          {'D', 'O', 'D', 'O'},
42                          {'O', 'O', 'O', 'O'},
43                          {'X', 'D', 'D', 'O'}};
44         System.out.println(minSteps(grid));
45     }
46 }
View Code

 

四、Two sum

topic:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

The nums = GIVEN [2,. 7,. 11, 15], target =. 9, 

Because the nums [ 0 ] + the nums [ . 1 ] + = 2. 7 =. 9, 
return [ 0 , . 1 ].
 
Solution:
The first (most In this way people think, the idea is simple, but high complexity):
 1 class Solution {
 2 
 3     public int[] twoSum(int[] nums, int target) {
 4         for (int i = 0, len = nums.length; i < len; i++) {
 5             for (int j = i + 1; j < len; j++) {
 6                 if (nums[i] + nums[j] == target) {
 7                     return new int[] { i, j };
 8                 }
 9             }
10         }
11         return new int[] { 0, 0 };
12     }
13 }
View Code

   The second (the lowest degree of complexity, around a bend on the idea, then HashMap):

 1 public int[] twoSum(int[] nums, int target) {
 2         Map<Integer, Integer> map = new HashMap<>();
 3         for (int i = 0; i < nums.length; i++) {
 4             int complement = target - nums[i];
 5             if (map.containsKey(complement)) {
 6                 return new int[] { map.get(complement), i };
 7             }
 8             map.put(nums[i], i);
 9         }
10         throw new IllegalArgumentException("No two sum solution");
11     }
View Code

 

 Three, LRU implementation

Ideas: hashMap + doubly linked list (as a doubly linked list, low complexity)

code show as below:

1  public  class Node <K, V> {
 2      Node <K, V> prev;
3,      the Node <the K, the V> next;
4      K k;
5      V v;
6  
7      public Node (K k, V v) {
 8          this .k = k;
9          the this .v = v;
10      }
 11 }
View Code
 1 public class LRUCache<K, V> {
 2 
 3     Node<K, V> head;
 4     Node<K, V> tail;
 5     HashMap<K, Node<K, V>> map;
 6     int capacity;
 7 
 8     public LRUCache(int capacity) {
 9         map = new HashMap<K, Node<K, V>>();
10         this.capacity = capacity;
11     }
12 
13     public V get(K key) {
14         Node<K, V> node = map.get(key);
15         if (node == null) {
16             return null;
17         }
18         V value = node.v;
19         // move node to tail
20         removeNode(node);
21         offerNode(node);
22         return value;
23     }
24 
25     public void put(K key, V value) {
26         if (map.containsKey(key)) {
27             Node<K, V> node = map.get(key);
28             node.v = value;
29 
30             // move node to tail
31             removeNode(node);
32             offerNode(node);
33         } else {
34 
35             // add to tail
36             Node<K, V> node = new Node<K, V>(key, value);
37             offerNode(node);
38             map.put(key, node);
39 
40             if (map.size() > capacity) {
41                 map.remove(head.k);
42                 removeNode(head);
43             }
44         }
45     }
46 
47     private void removeNode(Node<K, V> node) {
48         if (node.prev != null) {
49             node.prev.next = node.next;
50         } else {
51             head = node.next;
52         }
53 
54         if (node.next != null) {
55             node.next.prev = node.prev;
56         } else {
57             tail = node.prev;
58         }
59     }
60 
61     /*
62      * move node to tail
63      */
64     private void offerNode(Node<K, V> node) {
65         if (tail != null) {
66             tail.next = node;
67         }
68         node.prev = tail;
69         node.next = null;
70         tail = node;
71 
72         if (head == null) {
73             head = tail;
74         }
75     }
76 
77 }
View Code

 

First, to reverse a string

input:“abcde”

output:"edcba"

solution:

From the back, one by one into a new char array

 1 public String forReverse(String original) {
 2         char[] temp = original.toCharArray();
 3         StringBuffer sb = new StringBuffer();
 4         int tempLenth = temp.length;
 5         for (int i = tempLenth - 1; i >= 0; i--) {
 6             sb.append(temp[i]);
 7         }
 8         return sb.toString();
 9 
10     }

While exchanging ends (from both sides to the middle)

 1         String input = "Hello world"; 
 2         char[] temparray = input.toCharArray(); 
 3         int left, right=0; 
 4         right = temparray.length-1; 
 5   
 6         for (left=0; left < right ; left++ ,right--) 
 7         { 
 8             // Swap values of left and right 
 9             char temp = temparray[left]; 
10             temparray[left] = temparray[right]; 
11             temparray[right]=temp; 
12         } 
13   
14         for (char c : temparray) 
15             System.out.print(c); 

Both ends, the exchange (from the middle to both ends)

 1 public String forReverse2(String original) {
 2         char[] value = original.toCharArray();
 3         int count = value.length;
 4         int n = count - 1;
 5         for (int j = (n - 1) >> 1; j >= 0; j--) {
 6             int k = n - j;
 7             char cj = value[j];
 8             char ck = value[k];
 9             value[j] = ck;
10             value[k] = cj;
11 
12         }
13         return String.copyValueOf(value);
14     }

 

Second, in alphabetical order

Title: Given a string (which are all capital letters from A to Z, may be repeated), as "CAEEFDK". Allows you to re-sort.

Claim:

① must start with a consonant (as vowels: A, E, I, O, U, rest of the letters are all consonants)

②2 not consecutive consonants together

③2 not consecutive vowels together

Demand, after a given string, rearrange it, how many combinations you can?

example:

Given string "AAA", the number of combinations is 0

Given string "ABEK", the number of combinations is 4

Problem-solving algorithm is as follows (I think the algorithm is correct or not, discuss with friends who are interested):

class Solution {
    public int solution(String S) {
        int sum = 1;
        // null check
        if (S == null || S.length() == 0) {
            return 0;
        }

        // Divide into two groups
        StringBuilder vowel = new StringBuilder();
        StringBuilder consonant = new StringBuilder();
        char[] original = S.toCharArray();
        for (char temp : original) {
            if (temp == 'A' || temp == 'E' || temp == 'I' || temp == 'O' || temp == 'U') {
                vowel.append(temp);
            } else {
                consonant.append(temp);
            }
        }

        // All vowels
        String vowelS = vowel.toString();
        String consonantS = consonant.toString();
        if (consonantS.length() == 0) {
            return 0;
        }

        // vowelS length
        int countVowel = vowelS.length();
        // consonantS length
        int countconsonant = consonantS.length();
        if ((countconsonant - countVowel) != 1 && countVowel != countconsonant) {
            return 0;
        }

        int countSamll = countVowel < countconsonant ? countVowel : countconsonant;

        for (int i = 0; i < countSamll; i++, countconsonant--, countVowel--) {
            sum = sum * countconsonant * countVowel;
        }
        return sum;
    }
}
View Code

Problem-solving ideas, I will not say, write code, do not understand, we explore each other! If not correct place, pointing look.

 

Supplement. . . 2019/06/10 update

Guess you like

Origin www.cnblogs.com/lihao007/p/10865017.html