LeetCode229 MajorityElementII java题解

<p>题目:</p><p><span style="color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">Given an integer array of size </span><span style="box-sizing: border-box; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">n</span><span style="color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">, find all elements that appear more than </span><code style="box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 12.6000003814697px; padding: 2px 4px; color: rgb(199, 37, 78); border-radius: 4px; line-height: 30px; background-color: rgb(249, 242, 244);">? n/3 ?</code><span style="color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;"> times. The algorithm should run in linear time and in O(1) space.</span>
</p><p><span style="color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">求出现次数大于三分之一数组的长度,所以最多就只有2个这样的元素,题目要求线性时间复杂度和常数的空间复杂度,所以这题就不能使用哈希表来进行求解了。</span></p><p>通过第一次遍历找出出现次数最多的两个元素(利用此消彼长的原理),这时候不能得到具体出现多少次,所以得到两个出现次数最多的元素后,需要再遍历一次得到切确的出现次数看有没超过数组长度的三分之一</p><p>
</p><p>代码:</p>import java.util.ArrayList;
import java.util.List;

public class LeetCode229_MajorityElementII {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] nums={1,2,3,4,5,6,1,1,1,2,2,2,1,2};
		List<Integer> result=majorityElement(nums);
		for(int i=0;i<result.size();i++)
			System.out.println(result.get(i));

	}
	public static List<Integer> majorityElement(int[] nums) {

		List<Integer> result=new ArrayList<Integer>();
		int majorNum1=0,majorNum2=0,majorCount1=0,majorCount2=0;
		for(int i=0;i<nums.length;i++)
		{
			if(majorCount1==0)
			{
				majorNum1=nums[i];
				majorCount1=1;
			}

			else if(majorNum1==nums[i])
			{
				majorCount1++;
			}
			else if(majorCount2==0)
			{
				majorNum2=nums[i];
				majorCount2=1;
			}
			else if(majorNum2==nums[i])
			{
				majorCount2++;
			}
			else {
				majorCount1--;
				majorCount2--;
			}
		}
		majorCount1=0;
		majorCount2=0;
		for(int i=0;i<nums.length;i++)
		{
			if(nums[i]==majorNum1)
				majorCount1++;
			if(nums[i]==majorNum2)
				majorCount2++;
		}
		if(majorCount1>nums.length/3)
			result.add(majorNum1);
		if(majorCount2>nums.length/3&&majorNum2!=majorNum1)
			result.add(majorNum2);

		return result;

    }

}

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-14 18:21:36

LeetCode229 MajorityElementII java题解的相关文章

LeetCode71 Simplify Path java题解

题目: Given an absolute path for a file (Unix-style), simplify it. For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" 题解: 解题思路:这题是简化目录,每一级目录前面都有一个斜杠,我可以首先对斜杠进行分割,分割之后得到的结果无外乎4种情况:正常目录名称,空

LeetCode257 BinaryTreePaths(打印根节点到叶子节点的左右路径) Java题解

题目: Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / 2 3 5 All root-to-leaf paths are: ["1->2->5", "1->3"] 题解: 用深度优先遍历,类似二叉树的前序变遍历 代码: public class LeetCode257_BinaryTreePat

LeetCode108_Convert SortedArray to BinarySearchTree(将有序数组转成二叉排序树) Java题解

题目: Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 题解: 和我上面一篇将有序链表转成二叉排序树中用哈希表解的方法是一样的.基本思路:链表中间那个节点为树的根节点.根节点的左子树节点应该是根节点左边那部分的中间节点,根节点的右节点应该是根节点右边那部分链表的中间节点.后面就依照这个规律依次类推了. public static TreeNode s

LeetCode102 Binary Tree Level Order Traversal Java题解

题解: Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree {3,9,20,#,#,15,7}, 3 / 9 20 / 15 7 return its level order traversal as: [ [3], [9,20], [15,7] ] 解

LeetCode110 Blanced Binary Tree Java 题解

题目: Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 题解: 判断一颗二叉树是不是平衡二叉树  ,平衡二叉树是每个节

LeetCode234_PalindromeLinkedList (推断是否为回文链表) Java题解

题目: Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) time and O(1) space? 题解: 推断一个链表是不是回文的,这里要求O(n)时间复杂度和O(1)的空间时间复杂度.总共想了三种办法,三种办法都用到了两个指针,符合题目要求的仅仅有最后一种. 第一种办法:用数组倒着存前半段的链表的值.然后和后半段链表的值进行比較. 这样的解法执行的时间

LeetCode109_Convert Sorted List to Binary Search t题目tiTree(将链表转成二叉排序树) Java题解

题目: Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 题解:将一个有序链表转成二叉排序树,如果是一棵相对平衡的排序树,应该是这样的,链表中间那个节点为树的根节点,根节点的左子树节点应该是根节点左边那部分的中间节点,根节点的右节点应该是根节点右边那部分链表的中间节点,后面就按照这个规律依次类推了.知道上面的规律之后,问题的关键

TopCoder SRMS 1 字符串处理问题 Java题解

Problem Statement   Let's say you have a binary string such as the following: 011100011 One way to encrypt this string is to add to each digit the sum of its adjacent digits. For example, the above string would become: 123210122 In particular, if P i

LeetCode150 Evaluate Reverse Polish Notation java题解

题目: Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Some examples: ["2", "1", "+", "3", "*"]