编程题训练4
主元素
- 给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
样例
给出数组[1,1,1,1,2,2,2],返回 1
public class Solution {
/**
* @param nums: a list of integers
* @return: find a majority number
*/
public int majorityNumber(ArrayList<Integer> nums) {
// write your code
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0;i< nums.size();i++){
int num = nums.get(i);
if(map.containsKey(num)){
map.put(num,map.get(num) + 1);
}else{
map.put(num,1);
}
if(map.get(num) > nums.size()/2)
return num;
}
return 0;
}
}
加一
- 给定一个非负数,表示一个数字数组,在该数的基础上+1,返回一个新的数组。
该数字按照大小进行排列,最大的数在列表的最前面。
样例
给定 [1,2,3] 表示 123, 返回 [1,2,4].
给定 [9,9,9] 表示 999, 返回 [1,0,0,0]
public class Solution {
/**
* @param digits a number represented as an array of digits
* @return the result
*/
public int[] plusOne(int[] digits) {
// Write your code here
while(digits == null || digits.length ==0){
return digits;
}
int carryVal = 0;
int carry = 10;
for(int i = digits.length - 1; i >= 0; i--){
int num = digits[i];
if(num +1 == 10){
digits[i] = 0;
if(i == 0){
int[] a = new int[digits.length +1];
for(int j = 0; j < digits.length +1; j++){
if(j ==0){
a[j] = digits[j] +1;
}else{
a[j] = 0;
}
}
return a;
}
}else{
digits[i] = num+1;
return digits;
}
}
return digits;
}
}
将两个排序链表合并为一个新的排序链表
样例
给出 1->3->8->11->15->null,2->null, 返回 1->2->3->8->11->15->null。
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
public ListNode mergeTwoLists(ListNode head1, ListNode head2) {
// write your code here
if (head1 == null) {
return head2;
}
if (head2 == null) {
return head1;
}
ListNode root = new ListNode(0);
ListNode pointer = root;
// 当两个链表都不为空就进行合并操作
while (head1 != null && head2 != null) {
// 下面的操作合并较小的元素
if (head1.val < head2.val) {
pointer.next = head1;
head1 = head1.next;
} else {
pointer.next = head2;
head2 = head2.next;
}
// 将指针移动到合并后的链表的末尾
pointer = pointer.next;
}
// 下面的两个if有且只一个if会内的内容会执行
// 如果第一个链表的元素未处理完将其,接到合并链表的最后一个结点之后
if (head1 != null) {
pointer.next = head1;
}
// 如果第二个链表的元素未处理完将其,接到合并链表的最后一个结点之后
if (head2 != null) {
pointer.next = head2;
}
// 返回处理结果
return root.next;
}
}