total
总体.png
一、数据结构
二、排序算法
1. bubble
/**
* 原理:重复地走 访过要排序的数列,一次比较两个元素。
* i从0开始,i与i+1比较,如果i>i+1,那么就互换。
* @param array
* @return
*/
public static int[] pubbleSort(int array[]) {
int tmp;
boolean isChanged;
count = 0;
// 外层循环控制需要排序的次数
for (int i = 0; i < array.length - 1; i++) {
isChanged = false;
for (int j = 0; j < array.length - i - 1; j++) {
if (array[j] > array[j + 1]) {
tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
isChanged = true;
}
}
// if not changed, the array is sorted already.
if (!isChanged) {
break;
}
count++;
}
Log.d(TAG, "count: " + count);
return array;
}
2. Select
/**
* 原理:每一次从待排序的数据元素中选出最小(或最大)的一个元素,
* 存放在序列的起始(末尾)位 置,直到全部待排序的数据元素排完。
* @param array
* @return
*/
public static int[] selectSort(int array[]) {
count = 0;
for (int i = 0; i < array.length - 1; i++) {
int pos = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < array[pos]) {
pos = j;
}
}
if (pos != i) {
int tmp = array[i];
array[i] = array[pos];
array[pos] = tmp;
}
count++;
}
return array;
}
3. Insert
/**
* 原理:将一个数据插入到已经排好序的有序数据中。
* @param array
* @return
*/
public static int[] insertSort(int array[]) {
count = 0;
for (int i = 1; i < array.length; i++) {
int tmp = array[i];
int j = i - 1;
while (j >= 0 && array[j] > tmp) {
array[j + 1] = array[j];
j--;
}
array[j + 1] = tmp;
count++;
for (int k = 0; k < array.length; k++) {
Log.d(TAG, "count: " + count + " i: " + i + ", j: " + j + " [" + k + "]: " + array[k]);
}
}
return array;
}
三、leetcode
1. Add Two Numbers
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode list = new ListNode(0);
ListNode curr = list;
int carry = 0;
int sum = 0;
int ret;
while (l1 != null || l2 != null) {
ret = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0) + carry;
sum = ret % 10; // node的值
curr.next = new ListNode(sum);
carry = ret / 10; // 进位
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
curr = curr.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return list.next;
}
}