常用的技巧和知识点整合

来源:互联网 发布:头发少 知乎 编辑:程序博客网 时间:2024/05/22 06:12

1.在Array中取到一对一对的数,如1,2,3,4,5变成(1,2) (3,4) (5):

方法:

int i = 0;

for (; i < arr.length / 2; i++) {

int num1 = arr[i * 2];

int num2 = arr[i*2 + 1];

}

if (i * 2 < arr.length) {

int last = arr[i * 2];//个数为奇数的时候取得最后一位数字

}


2. Java中Arrays and Collections的转换

array --> list:

Integer[] arr = {1,2,3};//必须是Integer[] 而不是int[]

 List<Integer> list =Arrays.asList(arr);

list --> array:

List<String> list = new ArrayList<String>();

list.add(“abc”);

list.add(“def”);

list.add(“ghi”);

// tell the type information when forming the array.

String[] array = list.toArray(new String[0]);


List<Integer> list  = new ArrayList<Integer>();

Integer[] array = list.toArray(new Integer[0]);


注意:需要在转换的时候传入一个表明type的量


3.
Collections.reverseOrder() : reverse the natural order defined by a class implementing Comparable interface

PriorityQueue<Integer>maxHeap = new PriorityQueue<Integer>(11, Collections.reverseOrder());


4.数组的初始化:

 1D int[] 初始化: int[] test = {1,2,3,4,5};

2D int[][] 初始化: 

int[][] arr = {

{1,2,3,4,5,6},

{3,5,6,7}

}

注意: 每一row的元素数量可以不一样


向上取整:

比如说一个Bucket的size是5,我要求凡是超过5的都要新开辟一个bucket,则 (x - 1) / 5 + 1;

4. Arrays Utility相关操作

Arrays

http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

  • Arrays.sort(int[] array)


int[] array = new int[] {3, 2, 1};

Arrays.sort(array);

// array = {1, 2, 3};


  • Arrays.sort(T[], Comparator<T> comparator)

use the order defined in the comparator to sort the array.

class Cell {

 int x;

 int y;

 int value;

}


class CellComparator implementsComparator<Cell> {

 @Override

 public int compare(Cell c1, Cell c2) {

   if (c1.value == c2.value) {

      return 0;

   }

              return c1.value < c2.value ? -1 : 1;

 }

}


Cell[] cells = ...;

Arrays.sort(cells, new CellComparator());


OR:

Arrays.sort(pair, new Comparator<Pair>(){

@Override 

public int compare(Pairp1, Pairp2) {

return p1.val <= p2.val ? -1: 1;

}

});



  • Arrays.asList(T… a) -convert an array to a List


List<Integer> list = Arrays.asList(1, 2, 3);

// list is a List of [1, 2, 3]


  • Arrays.copyOf(original, intnewLength)


int[] array = new int[] {1, 2, 3};

int[] copy = Arrays.copyOf(array, 1);

// copy = {1}

copy = Arrays.copyOf(array, 5);

// copy = {1, 2, 3, 0, 0}, padding default values at the end

  • Arrays.copyRange(original, int from, int to)


int[] array = new int[] {1, 2, 3};

int[] copy = Arrays.copyRange(array, 1, 2);

// copy = {2}


  • Arrays.fill(original, value)


int[] array = new int[] {1, 2, 3};

Arrays.fill(array, 1);

// array = {1, 1, 1}


  • Arrays.toString(int[] array), Arrays.deepToString(int[][] matrix)


int[] array = new int[] {1, 2, 3};

String s = Arrays.toString(array);

// s = “[1, 2, 3]”;


  • Arrays.binarySearch(original, value)


int[] array = new int[] {3, 2, 1};

Arrays.sort(array);

// the array must be guaranteed to be sorted before using binarySearch.

int i = Arrays.binarySearch(array, 2);

// i = 1




Bit
取一个数的负数:
e.g.: -5

“complement of 5” + 1:

11111111111111111111111111111010

                                                  + 1

11111111111111111111111111111011

5 - 4 = 5 + (-4)

00000000000000000000000000000101

  •      + 11111111111111111111111111111100

00000000000000000000000000000001


Bit:

 

当说到kth位置的时候,是从leftmost开始算起,并且leftMost0th.

1 << 5 = 00000000 00000000 00000000 00100000 (mask)

 

String一个比较另类的输出:

System.out.println(“abc”.compareTo(“abc”));// 0

System.out.println(“abc”.compareTo(“abd”));// -1

System.out.println(“ab”.compareTo(“abcd”));// -2

System.out.println("abcd".compareTo("ab"));// 2

BrainStorm :

多种方式让计算机输出数字:example: printout :2

1.

System.out.println("abcd".compareTo("ab"));// 2

2.

System.out.println("2");

3.

System.out.println(2);

4.

1<< 1;



ArrayList中按值删除某个元素:
List<Integer> res = new ArrayList<>();
res.add(1);
res.add(2);
res.add(3);
res.remove(3) --- > would throw arrayIndexOutOfBound
res.remove(new Integer(3)); --->the right way 
原因:list.remove(E) api 中E指定的是index,如果放入的E的type是int的话,如果放入的type是Integer的话, 就是删除那个元素;


如何取得大于某个值的最小和小于某个值的最大?

publicclass BlackJackHand extends Hand {

 @Override

 public int score() {

   List<Integer>scores = possibleScores();

   int maxUnder = Integer.MIN_VALUE; // max score <= 21

   int minOver = Integer.MAX_VALUE; // min score > 21

   for(int score : scores) {

     if(score > 21 && score < minOver) {

       minOver= score;

     }else if (score <= 21 && score > maxUnder) {

       maxUnder= score;

     }

   }

   returnmaxUnder == Integer.MIN_VALUE ? minOver : maxUnder;

 }



判断符号是否一致的:

if (numerator< 0 ^ denominator < 0) return res += "-";判断两个符号是否一致的时候


LinkedHashMap 的Override:

publicstaticvoidmain(String[]args){

  LinkedHashMap lhm=newLinkedHashMap(MAX_ENTRIES+1,.75F,false){

 

  protectedbooleanremoveEldestEntry(Map.Entryeldest){//必须重写,因为在源码里面,是默认返回false的

  returnsize()> MAX_ENTRIES;

  }

  };


卡特兰数的公式以及代码实现:


for(inti=3;i<=100;i++){

            BigInteger sum=BigInteger.valueOf(0);

            for(intj=0;j<i;j++){

                sum=sum.add( ((BigInteger)list.get(i-1-j)).multiply( ((BigInteger) list.get(j) )) );

            }

            list.add(sum);

        }



需要用map或者set处理object时候,需要再objectclassoverride equals and hashCode,而不是用comparator


Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().


List<String>[]dp=newArrayList[s.length()+1]; //create generic array


常用性质:奇数 +偶数==奇数


https://leetcode.com/submissions/detail/32695572/



计算三角形的面积的方法:

1. 海伦公式(Heren) : s半周长 = (边长a + 边长b + 边长c) / 2, area = √{s (s - a)(s - b)(s - c)}

2.设A(x1,y1),B(x2,y2),C(x3,y3) 
由A-->B-->C-->A 按逆时针方向转.(行列式书写要求) 
设三角形的面积为S 
则S=(1/2)*(下面行列式) 
|x1 y1 1| 
|x2 y2 1| 
|x3 y3 1| 
S=(1/2)*(x1y2*1+x2y3*1+x3y1*1-x1y3*1-x2y1*1-x3y2*1) 
即用三角形的三个顶点坐标求其面积的公式为:
S=(1/2)*(x1y2+x2y3+x3y1-x1y3-x2y1-x3y2)


int 和 char之间的转换

int dig = 0;

System.out.println(dig+'0');// ouput: 48; '0'只是代码表着在char范围内的一个int 值 ,所以输出也是int

char a = '0';

System.out.println(a + 18);//output: 66// 同上原因

System.out.println((char)(66 +'0'));//output: r


StringBuilder sb =newStringBuilder();

sb.insert(0,1);// Line 1

sb.setCharAt(0,(char)48);// if not with Line 1, 将会抛出 string index out of range: 0;



     adaptive property: 意思就是对于almost sorted array O(n)的time complexity

     

    List<Integer>[]bucket=newArrayList[RADIX];

    记住不能写成List<Integer>[]bucket=newArrayList<Integer>[RADIX];

    //Cannot create a generic array of ArrayList

     

     

     

    //count the # of each charcter

    publicstaticbooleanisSame2(Stringstr,Stringother){

    if(str.length()!=other.length())returnfalse;

    int[] letters=newint[256];//assume to be ASCII

    char[] chr=str.toCharArray();

    for(char c: chr){

    letters[c]++;

    }

    for(int i=0; i<other.length(); i++){

    //first we assure that the length of two string is same

    //then if one char is not same it must cause certain char number below 0;

    if(--letters[other.charAt(i)]<0){

    returnfalse;

    }

    }

    returntrue;

    }

     

     

    Balanced tree 意思是the depth of subtree wil not vary by more than a certain amount,并不是一定要为1

     

     

    Enum 使用:

    classNode{

    State state;

    List<Node> neighbors=newArrayList<>();

    Node(Statestate){

    this.state =state;

    }

    publicList<Node>getAdjacent(){

    return neighbors;

    }

    }

     

     

    publicenum State{//相当于定义了一个class

    Unvisited, Visited, Visting;

    }

     

    if(u.state= State.Visited)//前面记着要标明type ==> State

     

     

    X ^ 1s = ~x

     

     

    不同type的数字可以相互比较.

     

     

     

    倒水问题,两个jug如果是互为prime,(没有共同primefactor,那么总能 找到倒满1 ~ sum的倒水序列。

     

    负数的位运算表示 = 正数的位运算取反 + 1;

     

    8 == 1000

    如果想取到rightmost 1并且包括后面的0,就 a &= -a;

    (原理: a的负数是a取反,+1得到,所以如果a中右边第一个1的右边有x个0的话,取反后都是1,再+1的话,刚好取得a中rightmost 1 的位置)

     

     

    lg(n-1) + lg(n-2) + ... + lg(1) ~ O(lg(n!)) ~ O(nlgn)

     

     

     

    cartesian plane : 直角坐标系

     

    Don't assumethat the slope and y-intercept are integers.

     

    Java doubles will hold their precision better than your given epsilon of 0.00001.

     

    Understand limitations of floating point representations. Never check for equality with ==. Instead, check if the difference is less than anepsilon value.

     

    if(!(a<0^b<0)){//using XOR

    return x;

    }

    !(a < 0 ^ b < 0) == a < 0 && b < 0 || a > 0 && b > 0

     

     

    凡是用到Math.pow()都要注意如果想用Int,要强制转换

     

     

    newPOJ3984MazeDFS(maze).go();//可以直接这样执行

     

     

    Java 中 label的作用:

    Label :

    While() {

    While() {

    break label;

    }

    }

     

     

     

    可以跳出label所涵盖的代码,否则只能跳出里层while()

     

     

     

     

    // 常规求法

    publicstaticintpow1(inta,intb){

    int r =1;

    while(b-->0){

    r *=a;

    }

    return r;

    }

     

    // 二分求幂

    publicstaticintpow2(inta,intb){

    int r =1, base=a;

    while(b!=0){

    if(b%2!=0){//奇数时

    r *= base;

    }

    base *= base;

    b/=2;

    }

    return r;

    }

     

    // //11的二进制是1011

    // 11 = 2³×1 + 2²×0 + 2¹×1 + 2º×1

    // 因此,我们将a¹¹转化为算 a^(2 ^ 0) *a^(2 ^ 1) *a^(2 ^ 3);

    publicstaticintintpow3(inta,intb){

    int r =1, base=a;

    while(b!=0){

    // b & 1 用来检测b是否是奇数,主需要看最后一位,因为其他为都是2的倍数,加起来还是2的倍数

    // 如果是奇数,那么最低位一定是1

    if((b&1)!=0){//结果其实是跟b的二进制表达式中1相关,而其中0的作用是使乘数变大

    r *= base;

    }

    base *= base;

    b>>=1;

    }

    return r;

    }

     

    Bit 来完成 multiply:

     

    publicstaticinthelper(inta,intb){

    int base =0;

    int res =0;

    while(b!=0){

    int last =b&1;

    if(last!=0){

    res +=a<< base;

    }

    base++;

    b>>=1;

    }

    return res;

    }

     

     

    例如 8 与 10 的最大公约数是 2,不是 1,因此它们并不互质。

    又例如 71013 的最大公约数是 1,因此它们互质。

    如果两个数是互质数,那么它们的最大公约数是1,最小公倍数是这两个数的乘积。

    例如8和9,它们是互质数,所以(8,9)=1,[8,9]=72。

    两个数的最大公约数与它们的最小公倍数的乘积等于这两个数的乘积。 

     

     

    Euclid[英][ˈju:klid] Algorithm : 亚里士多德算法(辗转相除法)求最大公约数:

     

     

    //Euclid's Algorithm [ˈju:klid], recursive solution

    publicstaticintdivisor1(intm,intn){

    if(m%n==0){

    returnn;

    }else{

    returndivisor1(n,m%n);

    }

    }

    //iterative solution

    publicstaticintdivisor2(intm,intn){

    while(n!=0){

    int x =m%n;

    m=n;

    n= x;

    }

    returnm;

    }

     

     

     

    什么时候需要backtracking? 当为了达到一定的要求,而必须先进行一些列的动作,然而在执行中,如果不符合,需要回到上一个节点选择其他路径的时候,用backtracking.

     

    当需要达到的要求比较模糊,并没有明确说明要XX长度,xx个数的时候,不用backtracking的可能性大一些;

     

     

     

    StringBuilder insert vs setCharAt:

     

    Insert 是插入,insert(0, dig) 相当于每次在头部加入一个dig;

    其中dig是所有stringbuilder可以自动转换的类型(eg: int)

     

    setCharAt(0, dig) : 是将位于0位置的字符Update成dig,其中dig必须是char类型

     

     

     

     while (left < right) {//交换的时候要用小于号,不能用!=

     

     

    Substring :

     

    String str = "abc";

    System.out.println(str.substring(0,0)); // ==> ''()

    System.out.println(str.substring(1,2));// ==> b

     

     

    Java 默认PriorityQueue是minHeap

     

     

    Java 中只有Primitive可以不用赋值,系统会自动赋值,其他的object都需要手动赋值,哪怕是null;构造函数除外

     

    // 切记char array to String 用 new String(chr),不能用chr.toString();

     

     

     

    public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

    length : 要从scr中copy多少

     

     int slash = s.indexOf('/', i);//从i位置开始找第一个'/'出现的位置

     

    ArrayList remove 的是index

    Map remove的是值,因为是键值对

     

     

     

    List<Integer> sub = list.sublist(start, end);

    Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.)

     

    List.toStirng(): 能将integer以string形式输出

     

    1.List<Integer> list = new ArrayList<>();

    2.List<Integer> list = new LinkedList<>();

    Interface 一样,implement不一样, 实现的性能也不一样, list.remove(0),  1.的复杂度是O(n), 2.复杂度是O(1)

     

     

    If two objects have same hash it means that they may or may not be equal (though two equal objects are required to have same hash)

     

    Map 里面: 用entrySet()和keySet(), 而对于value,用values();

     

     

     An integer n has log(n) bits, 举例来说,8 = 2 ^3 =  (1000) > (111) == 7, 即2 ^ 4 > 2 ^3 + 2 ^ 2 + 2 + 1

     

    如何将最低位的1变成0呢,在Bit中,用n & (n - 1)

     

     

    用/和%时, a/b 或者 a%b时, a需要是以0开始的index,b需要是总的个数, 当a是以1开始的Index时,需要用

    (a-1) %b 来定位a的位置

     

    Tree 的 height是取最高的

     

     public int getHeight(TreeNode root) {

            if(root == null) return 0;

            return Math.max(getHeight(root.left), getHeight(root.right)) + 1;

        }

     

     

    因此线段树是完全二叉树,对于包含n个叶子节点的完全二叉树,它一定有n-1个非叶节点,总共2n-1个节点

    完全二叉树,定义, 每一层都满,除了最后一层

     

     

    取反符号的优先级高于除法运算符

    Val = 0

    System.out.println(-((Integer.MIN_VALUE +val)/ 10)); ==》 214748364

    System.out.println(-(Integer.MIN_VALUE +val)/ 10); ==> 1.先 -Integer.MIN_VALUE, 然后overflow, 得到依然是Integer.MIN_VALUE,然后/10,得到-214748364;

     

     

    Int a = 3 == 011(2);

    -a = ~a + 1;

    取得a中从右往左第一个1连同后面的0,方法 : a &= -a 或者 a &= ~a + 1;

     

     

     Collections.reverse(res); // 2,3,1 ----> 1,3,2

    Collections.sort(res, Collections.reverseOrder()); // 2,3,1 ---->  3,2,1

     

     

    Final and Finally in java

     

    Weak reference in java

     

    Polymorpham , examples

     

    Abstract class vs interface

     

    How to inherit multiple abstract class

     

     

     

     

    Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.[From JavaDoc : All the classes inherit a basic hash scheme from the fundamental base class java.lang.Object, but instead many override this to provide a hash function that better handles their specific data. ][ There's no requirement that hash values be consistent between different Java implementations, or even between different execution runs of the same program]

    Therefore, you should not use the hash code in distributed applications. A remote object may have a different hash code than a local one, even if the two are equal.

     

    You may know that cryptographic hash codes such as SHA1 are sometimes used to identify objects (Git does this, for example).  SHA1 uses 160-bit keys, which makes collisions virtually impossible.

     

     

     

     

    JAVA Sring:

    Boolean Str.startsWith(pattern, startPosition);

     int slash = s.indexOf('/', i); //starts from ith position, try to find the posion of /;

     List<Integer> temp = …..;//<1,2,3,4>

    String str = temp.toString();//==>  "1234"

     

    (a * b) mod x = (a mod x) * (b mod x)

     

    1 << x 意思是2 ^ x

     

    2 << (x - 1) == 1  << X

     

     

     

    1. if (nums == null)
    2.     throw new IllegalArgumentException("nums's reference is null");

     

    Integer.toString(res)

    Integer.parseInt(str);

     

    TrieTree time complxity:

    The complexity of creating a trie is O(W*L), where W is the number of words, and L is an average length of the word: you need to perform L lookups on the average for each of the Wwords in the set.

     

     

    private void swap(int[] A, int a, int b) {
        A[a] ^= A[b];
        A[b] ^= A[a];
        A[a] ^= A[b];
    }

     

     

    Following is the declaration for java.util.Arrays.copyOfRange() method

    publicstaticshort[] copyOfRange(short[] original,intfrom,int to)

    Parameters

    • original -- This is the array from which a range is to to be copied.
    • from -- This is the initial index of the range to be copied, inclusive.
    • to -- This is the final index of the range to be copied, exclusive.

    Return Value

    This method returns a new array containing the specified range from the original array, truncated or padded with zeros to obtain the required length.

     

     

    List<String> res = Arrays.asList("1", "8", "0");

    List<Integer> list = new ArrayList<Integer>(map.values());

     

     

    if ((bound & -bound) == bound)  // i.e., bound is a power of 2

    -boud: 是先每一位取反,然后加1;

     

    另一个判断power of 2的方法是: (bound & (bound - 1)) == 0

     

    Arrays.fill (arr, 1); 只能接受一维的数组!


http://stackoverflow.com/questions/18445158/int-vs-integer-comparison-java



用Scanner 来处理String 中heading/trailing spaces. Scanner Scanner which by default will split by whitespace (and remove leading/trailing whitespace):


public String reverseWords(String s) {
        Scanner parts = new Scanner(s);
        String res = "";
        while(parts.hasNext()){
            res = parts.next() + " " + res;
        }
        return res.trim();// since in while loop we add space to the last word anyway.
    }




0 0
原创粉丝点击