
- public int[] twoSum(int[] nums, int target) {
- int[] out = new int[ 2 ];
- for ( int i = 0; i < nums.length; i ++ ) {
- for ( int j = 0; j < nums.length; j ++ ) {
- if ( j == i )
- continue;
- if ( nums[ i ] + nums[ j ] ==target ) {
- out[0] = i;
- out[1] = j;
- return out;
- }
- }
- }
- return out;
- }

总水量 = 所有的水池装的水之和 = 所有水池中的每个 i 位置的装水量相加之和
所有的水池是由 一跟柱子height[ i ] + 后面的第一根>=height[ i ] 的柱子组成的
也就是说,水池的左边边界柱子(也是水池装水的最高高度),必须是后面还有高度不低于它的柱子才可以
- public int trap( int[] height ) {
- if ( height.length == 1 || height.length == 0)
- return 0;
- int max = 0;
- int n = height.length;
- int h = height[ 0 ], hIndex = 0;
- // 遍历找出第一个樯的高度 != 0 的下标,因为只有在非0的墙后面才可能装水
- for( int k = 0; k < n; k ++ ) {
- if( height[ k ] != 0 ) {
- h = height[ k ];
- hIndex = k;
- for ( int i = k; i < n; i ++ ) {
- System.out.print( i +"》");
- boolean f = false;
- if ( i == hIndex ) {
- f = true;
- h = height[ hIndex ];
- int j = 0;
- // 寻找后面比目前最高的墙还高的墙的下标
- while ( h >= 0 ) {
- boolean flag = false;
- for (j = i + 1; j < n; j++) {
- if (height[j] >= h) {
- hIndex = j;
- System.out.print("[" + hIndex + "]");
- flag = true;
- break;
- }
- }
- if ( flag )
- break;
- // 后见没有比现在最高的高度h高的墙,就h--,再继续遍历后面的寻找
- if (j == n) {
- h --;
- continue;
- }
- }
- }
-
- // 加上本i位置所能装的水量(最高的墙 - 本i位置的墙的高度)
- if ( !f ) {
- max += h - height[i];
- System.out.print(h - height[i] + " ");
- }
- }
- break; // 找到非0的墙后,break掉
- }
- }
- System.out.println();
- return max;
- }


递归
- static List<List<Integer>> list = new ArrayList<>();
- String str = "";
- public List<List<Integer>> subsets(int[] nums) {
- for ( int j = 0; j < nums.length; j ++ ) {
- List<Integer> list1 = new ArrayList<>();
- list1.add( nums[ j ] );
- getResult( nums, list1, j + 1 );
- }
- getResult( nums, new ArrayList<>(), 0 );
- return list;
-
- }
-
- private void getResult(int[] nums, List<Integer> integerList, int i) {
-
- String s = "[";
- for( int j = 0; j < integerList.size(); j ++ ) {
- s += integerList.get( j );
- }
- s += "]";
- if( ! str.contains( s ) ) {
- str += s + "---";
- list.add(new ArrayList<>(integerList));
- }
-
- if ( i == nums.length )
- return;
-
- for ( int j = i; j < nums.length; j ++ ) {
- List<Integer> list2 = new ArrayList<>( integerList );
- list2.add( nums[ j ] );
- getResult( nums, list2, j + 1 );
- }
- }
成功90%,最后一个用例显示解答错误,也不知道什么原因,也不应该是超时,因为我直接测试了最大范围的用例,运行时间27ms而已,哎不知道啥错误原因
