Tag:Array

905.Sort Array By Parity

Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

思路很简单,但我的代码过于冗余
较优代码:

public int[] sortArrayByParity(int[] A) {
        for (int i = 0, j = 0; j < A.length; j++)
            if (A[j] % 2 == 0) {
                int tmp = A[i];
                A[i++] = A[j];
                A[j] = tmp;;
            }
        return A;
    }

我的代码

class Solution {
    public int[] sortArrayByParity(int[] A) {
        int high= A.length -1;
        int low =0;
        while(low < high)
        {
            if(A[low]%2 == 1)
            {
                if(A[high]%2 == 1)
                    high--;
                else if(A[high]%2 == 0)
                {
                    int temp = A[low];
                    A[low] = A[high];
                    A[high] = temp;
                    high--;
                    low++;
                }
                
            }
            else if(A[low]%2 == 0)
                low++;
        }
        return A;
        
    }
}

950. Reveal Cards In Increasing Order

In a deck of cards, every card has a unique integer. You can order the deck in any order you want.
Initially, all the cards start face down (unrevealed) in one deck.
Now, you do the following steps repeatedly, until all cards are revealed:
Take the top card of the deck, reveal it, and take it out of the deck.
If there are still cards in the deck, put the next top card of the deck at the bottom of the deck.
If there are still unrevealed cards, go back to step 1. Otherwise, stop.
Return an ordering of the deck that would reveal the cards in increasing order.
The first entry in the answer is considered to be the top of the deck.

思路:
step1、将数组排序
step2、将数组的index push到队列中,模拟牌的操作,每一轮依次将排序过后的数组中的元素赋给队头元素代表的index
step3、循环n次
代码如下:

class Solution {
    public int[] deckRevealedIncreasing(int[] deck) {
        Arrays.sort(deck);
        int len = deck.length;
        int[] res = new int[len];
        Queue que = new LinkedList<>();
        for(int i = 0;i< len;i++)
            que.add(i);
        for(int i = 0;i

Queue API:
poll():删除并返回队头元素
peek():取队头元素

283. Move Zeroes

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.

思路:使用insert index
step1、遇到非零元素则将其插入到insertindex处
step2、用零填充剩余元素

class Solution {
    public static void moveZeroes(int[] nums) {
        
        int insertPos = 0;
        for(int i = 0;i

238. Product of Array Except Self

Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

思路:
step1、from left to right:用result数组存放前index-1个数的乘积
(result[0]初始化为1),即{1,nums[0],nums[0]×nums[1].......}
step2、from right to left:初始化temp = 1,从右往左将 temp×result[i] 存入result数组,更新temp = nums[i]*temp

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] res = new int[nums.length];
        for(int i = 0,temp = 1;i=0;i--)
        {
            res[i] = temp*res[i];
            temp = temp*nums[i];
        }
        return res;
    }
}

448. Find All Numbers Disappeared in an Array

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]

思路:利用index的唯一性
step1、由于1 ≤ a[i] ≤ n (n = size of array),先将a[i] - 1,使其与index相对应,再将nums[a[i]-1]取反
step2、遍历数组,判断nums[i]是否大于零,若大于零,则index + 1即为缺失的元素

class Solution {
    public List findDisappearedNumbers(int[] nums) {
        List res = new ArrayList<>();
        for(int i = 0;i 0)
                 nums[var] = -nums[var];
        }
        for(int i = 0;i 0)
                res.add(i+1);
        }
        return res;
    }
}

169. Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2

思路:
法1:brute force
法2:将数组排序,When an element appears more than n/2 times in the array, the middle one must be the "majority" number when array is sorted.
法3:Boyer-Moore Voting Algorithm

法2代码:

class Solution {
    public int majorityElement(int[] nums) {
        // //brute force
        // int len = nums.length/2;
        // for(int i = 0;i len)
        //         return nums[i];
        // } 
        // return -1;
        Arrays.sort(nums);
        return nums[nums.length/2];
    }
}

法3代码:

public class Solution {
    public int majorityElement(int[] num) {

        int major=num[0], count = 1;
        for(int i=1; i

Backtracking Problem

78. Subsets

Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output:
[ [3],[1],[2],[1,2,3],[1,3],[2,3],[1,2],[]]

思路:回溯法。对Input中每一个元素而言,在Output中只存在两种状态:加入与未加入。
step1、从Index = 0开始深度优先遍历
step2、由于子问题规模减一,采用递归处理
step3、回溯到开始节点


test.jpg
class Solution {
    public List> subsets(int[] nums) {
        List> res = new ArrayList>();
        List subset = new ArrayList();
        dfs(res,subset, nums, 0);
        return res;
    }
    private void dfs(List> res, List subset, int[] nums, int startIndex)     {
        res.add(new ArrayList(subset));
        for(int i = startIndex; i < nums.length; i++) {
            subset.add(nums[i]);  //① 加入 nums[i]
            dfs(res, subset, nums, i + 1);  //② 递归
            subset.remove(subset.size() - 1);  //③ 移除 nums[i](回溯)
        }
    }
}

22. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))", "(()())",
"(())()",
"()(())",
"()()()"
]

思路:回溯法。jvm执行过程还不理解

class Solution {
    public List generateParenthesis(int n) {
        
//         backtracking
//         curr: 当前string状态
        List res = new ArrayList();
        if(n == 0)
            return res;
        helper("",res,n,0,0);
        return res;
        
    }
    public static void helper(String curr,List res,int n,int left,int right)
    {
        if(right == n)
        {
            res.add(curr);
            return;
        }
        if(left < n)
        {
            helper(curr + "(",res,n,left + 1,right);
        }
        if(right < left)
        {
            helper(curr + ")",res,n,left,right + 1);
        }
    }
}

39. Combination Sum

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
Example 2:
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]

思路:回溯法。

class Solution {
    public List> combinationSum(int[] candidates, int target) {
        
        List> results = new ArrayList>();
        if(candidates.length == 0 || candidates == null)
            return results;

        Arrays.sort(candidates);
        
        List combination = new ArrayList<>();
        toFindCombination(results,combination,candidates,target,0);
        return results;
    }
    private void toFindCombination(List> results,List combination,int[] candidates,int target,int start)
    {
        if(target == 0)
        {
            results.add(new ArrayList<>(combination));
            return;
        }
        for(int i = start;i< candidates.length;i++)
        {
            if(candidates[i] > target)
                break;
            combination.add(candidates[i]);
            toFindCombination(results,combination,candidates,target - candidates[i],i);
            combination.remove(combination.size() - 1);
        }
    }
}

你可能感兴趣的:(Tag:Array)