、118

//283
public class Solution {
    public void moveZeroes(int[] nums) {
        int flag = 0;
        for(int i=0; i<nums.length; i++) {
            if(nums[i] != 0) {
                nums[flag++] = nums[i];
            }
        }
        if(flag!=nums.length) {
            for(int i=flag; i<nums.length; i++)
                nums[i] = 0;
        }
    }
}
//268
public class Solution {
    public int missingNumber(int[] nums) {
        boolean[] flags = new boolean[nums.length+1];
        for(int i : nums)   flags[i] = true;
        int rst = 0;
        for(int i=0; i<flags.length; i++)
            if(!flags[i])
                rst = i;
        return rst;
    }
}
//1
//使用一个hashmap来记录target-nums[i]以前是否出现过,来使n*n变为线性的。
public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] rst = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i=0; i<nums.length; i++) {
            if(map.containsKey(target-nums[i])) {
                rst[0] = map.get(target-nums[i]);
                rst[1] = i;
            }
            map.put(nums[i], i);
        }
        return rst;
    }
}
//26
//是一个已经排序了得数组
public class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums.length == 0)    return 0;
        int flag = 0;
        for(int i=1; i<nums.length; i++) {
            if(nums[i] > nums[flag])
                nums[++flag] = nums[i];
        }
        return flag+1;
    }
}
//27
public class Solution {
    public int removeElement(int[] nums, int val) {
        int flag = 0;
        for(int i=0; i<nums.length; i++) {
            if(nums[i] != val)  nums[flag++] = nums[i];
        }
        return flag;
    }
}
//27-->(2)
public class Solution {
    public int removeElement(int[] nums, int val) {
        int flag = 1;
        Arrays.sort(nums);
        for(int i=0; i<nums.length; i++) {
            if(nums[i] == val) {
                flag = 1;
                while(++i<nums.length && nums[i] == val) flag++;
                i = nums.length;
            }
        }
        return nums.length-flag;
    }
}
//35
public class Solution {
    public int searchInsert(int[] nums, int target) {
        int flag = 0;
        for(int i=0; i<nums.length; i++) {
            if(nums[i] < target) {
                flag++;
            }
        }
        return flag;
    }
}
/118
public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> rst = new ArrayList<List<Integer>>();
        List<Integer> row, pre = null;
        for(int i=0; i<numRows; i++) {
            row = new ArrayList<Integer>();
            for(int j=0; j<=i; j++) {
                if(j==0 || j==i)  row.add(1);
                else row.add(pre.get(j-1) + pre.get(j));
            }
            pre = row;
            rst.add(row);
        }
        return rst;
    }
}
posted @ 2017-02-26 22:04  StevenLuke  阅读(122)  评论(0编辑  收藏  举报