LeetCode刷题系列(十六)Some Little Questions

来源:互联网 发布:海奇软件app 编辑:程序博客网 时间:2024/06/07 10:39

  本篇给出了几道并没有太多技巧的的小问题。

Reverse Words in a String

  这道题倒转一个字符串中所有的单词。

public String reverseWords(String s) {    if (s == null || s.length() == 0) {        return "";    }    String[] array = s.split(" ");    StringBuilder sb = new StringBuilder();    for (int i = array.length - 1; i >= 0; --i) {        if (!array[i].equals("")) {            sb.append(array[i]).append(" ");        }    }    //remove the last " "    return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);}

Partition Array

  这道题为划分数组。将数组中小于k的数移到左边,大于等于k的数移到右边。这道题也借助了两个指针的方法。

public int partitionArray(int[] nums, int k) {    //write your code here    if(nums == null || nums.length == 0){        return 0;    }    // //dummy number    // nums.add(k);    int i = 0;    int j = nums.length - 1;    for(; i <= j; i++){        if(nums[i]< k){            continue;        }        while(j >= i && nums[j] >= k){            j --;        }//while        //i points to a number >= k        //j points to a number < k        //swap i and j        if(j >= 0 && i < j){            int tmp = nums[i];            nums[i] = nums[j];            nums[j] = tmp;            j --;        }    }//for   // nums.remove(j + 1);    return j + 1;}

Interleaving Positive and Negative Numbers

  这道题为交错正负数。将正数和负数互相交叉,需要注意的是数量多的放在前面,如果正数多则第一个数为正数。我们使用两个数组分别挑出正数和负数,然后交错放在原数组里。

public int[] subfun(int[] A,int [] B, int len) {    int[] ans = new int[len];    for(int i = 0; i * 2 + 1 < len; i++) {        ans[i * 2] = A[i];        ans[i * 2 + 1] = B[i];        }    if(len % 2 == 1)        ans[len - 1] = A[len / 2];    return ans;}public void rerange(int[] A) {    int[] Ap = new int[A.length];    int totp = 0;    int totm = 0;    int[] Am = new int[A.length];    int[] tmp = new int[A.length];    for(int i = 0; i < A.length; i++)        if(A[i] > 0)            {                Ap[totp] = A[i];                totp += 1;            }        else            {                Am[totm] = A[i];                totm += 1;              }       if(totp > totm)        tmp = subfun(Ap, Am, A.length);    else        tmp = subfun(Am, Ap, A.length);    for (int i = 0; i < tmp.length; ++i)        A[i] = tmp[i];}
0 0
原创粉丝点击